6

I have an array of objects and I need to delete few of the objects based on conditions. How can I achieve it using lodash map function? Ex:

[{a: 1}, {a: 0}, {a: 9}, {a: -1}, {a: 'string'}, {a: 5}]

I need to delete

{a: 0}, {a: -1}, {a: 'string'}

How can I achieve it?

Pradeep Rajashekar
  • 565
  • 2
  • 9
  • 18

4 Answers4

9

You can use lodash's remove function to achieve this. It transforms the array in place and return the elements that have been removed

var array = [{a: 1}, {a: 0}, {a: 9}, {a: 5}];
var removed = _.remove(array, item => item.a === 0);

console.log(array);
// => [{a: 1}, {a: 9}, {a: 5}]

console.log(removed);
// => [{a: 0}]
klugjo
  • 19,422
  • 8
  • 57
  • 75
2

ES6

const arr = [{a: 1}, {a: 0}, {a: 9}, {a: 5}];

const newArr = _.filter(arr, ({a}) => a !== 0);

ES5

var arr = [{a: 1}, {a: 0}, {a: 9}, {a: 5}];

var newArr = _.filter(arr, function(item) { return item.a !== 0 });

https://lodash.com/docs/4.17.4#filter

Joey
  • 1,075
  • 8
  • 13
1

Other then _.remove or _.filter you can also use reject()

var array = [{a: 1}, {a: 0}, {a: 9}, {a: 5}];
var result = _.reject(array , ({a}) => a===0 });

console.log(result);//[{a: 1}, {a: 9}, {a: 5}]

https://jsfiddle.net/7z5n5ure/

Emad Dehnavi
  • 3,262
  • 4
  • 19
  • 44
-1

use this pass arr, key on which you want condition to apply and value is value of key you want to check.

function removeElem(arr,key,value){
    return arr.filter(elem=>elem[key]===value)
}