Is there a better way to remove an element from a JS array from the functional programming point of view?

Asked

Viewed 52 times

1

I was trying to remove an element from an array, and since I’m trying to learn a little bit more about functional programming, I tried to change the old way I used to do this.

const myArray = [
  {id: 1, label: 'first'},
  {id: 2, label: 'second'},
  {id: 3, label: 'third'},
]

const itemToRemove = {
	id: 2,
  label: 'second'
}

myArray.splice(myArray.findIndex(item => {
	return item.id == itemToRemove.id
}), 1)

console.log('->', JSON.stringify(myArray, null, 2))

My question is... Is there a better way to join (chain) these two functions? There is a better way to do this (from the point of view of functional programming)?

Thank you very much.

  • what are the two functions you want to join ? splice and findIndex ?

  • 1

    Exact, or at least was the initial idea (before the @Rgio consideration)

2 answers

1

One of the paradigms of functional programming is not to change data outside a given function. That is to say to have immutable structures and pure functions. The splice goes in the opposite direction and changes an array without creating a copy. And this can have unwanted consequences.

To filter elements of an array with functional programming principles, the .filter and create another array, or if it is desired to over-write the variable. In either case the original array is unchanged.

const myArray = [
  {id: 1, label: 'first'},
  {id: 2, label: 'second'},
  {id: 3, label: 'third'},
]

const itemToRemove = {
	id: 2,
  label: 'second'
}

// comparando os objetos transformados em string
const filtrada1 = myArray.filter(
    el => JSON.stringify(el) != JSON.stringify(itemToRemove)
);
console.log(1, JSON.stringify(filtrada1));

// se bastar comparar com o `id`
const filtrada2 = myArray.filter(
    ({id}) => id != itemToRemove.id
);
console.log(2, JSON.stringify(filtrada2));

0

I believe this would be the ideal answer if you are looking for simplicity and functional programming, using the function grep():

var obj =  [ {id: "1", name: "Ola"}, 
            {id: "2", name: "Java"}, 
            {id: "3", name: "Script"}];
obj = $.grep(obj , function (value) {
        return value.id != '1';
});

console.log(obj);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Example of Syntax:

retorno = $.grep(ObjetoASerRemovido, function (value) {
        // aqui pode ser a condição que preferires ex: value.name != 'Ola' && value.id != '1'
        return value.id != '1';
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.