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

1

I was trying to remove an element from an array, and since I'm trying to learn a 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 there a better way to chain these two functions? Is there a better way to do this (from the point of view of functional programming)?

Thank you very much.

    
asked by anonymous 27.08.2017 / 19:51

2 answers

2

One of the paradigms of functional programming is not to change data outside of a given function. That is to have immutable structures and pure functions. 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, you must use .filter and create another array, or if you want to overwrite the variable. In both cases 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));
    
27.08.2017 / 20:13
0

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

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>

Syntax example:

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