Search code examples
javascriptnode.jslodash

What is the best way to delete objects from Array


I am wondering if what is the best way to find all Indexes of objects in an Array and then delete them from the Array. Currently, my code looks like as below;

  var data = _.find(group.value, function(valueItem){ return valueItem.value == filter.value });
  var index =_.indexOf(group.value,data);
  group.value.splice(index,1);

This works great, but only gets me the first index if the index is more than once. So, I am looking for a method that will get me all indexes in my Array, so I can loop through in remove all


Solution

  • Use filter to create a new array of objects.

    Based on your example this code creates new arrays based on the value (name) of each value property. I've wrapped the filter code in a function (getData) that you can call with the original array and the name you want to check as arguments.

    If there is no match the function will return an empty array.

    const arr = [
      { id: 1, value: 'bob' },
      { id: 2, value: 'dave' },
      { id: 3, value: 'bob' },
      { id: 4, value: 'bob' }
    ];
    
    function getData(arr, name) {
      return arr.filter(obj => obj.value === name);
    }
    
    console.log(getData(arr, 'bob'));
    console.log(getData(arr, 'dave'));
    console.log(getData(arr, 'mary'));