Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript remove multiple values of array of objects

I am new to javascript and I am trying to remove multiple values from an array of objects.

Right now I can remove one object like this

if(obj.findObjectByKey(response, 'cat_id', 171) == true) {
    var catId = response.map(item => item.cat_id).indexOf(171);
}

In the code above I will remove the item with a id of "171" but now I have an array with multiple values that I would like to remove.

So how can I modify the code above to let me pass in an array of items that I want to remove from the list eg ['171', '172', '173, '174'];

like image 754
Kiow Avatar asked Jan 15 '18 19:01

Kiow


1 Answers

If you can use ES6, try using JavaScript's filter and includes for this.

const nums = [1, 2, 3, 4, 5, 6];
const remove = [1, 2, 4, 6];

function removeFromArray(original, remove) {
  return original.filter(value => !remove.includes(value));
}

console.log(removeFromArray(nums, remove));

This will work just as well with strings.

const nums = ["1", "2", "3", "4", "5", "6"];
const remove = ["1", "2", "4", "6"];

function removeFromArray(original, remove) {
  return original.filter(value => !remove.includes(value));
}

console.log(removeFromArray(nums, remove));

This solution also has the added benefit of being immutable. Meaning that you are returning new data rather than morphing the old. Which is considered good practice.

https://wecodetheweb.com/2016/02/12/immutable-javascript-using-es6-and-beyond/

like image 183
Devan Buggay Avatar answered Oct 15 '22 17:10

Devan Buggay