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?
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?
Share Improve this question edited Nov 22, 2017 at 6:27 Pradeep Rajashekar asked Nov 22, 2017 at 5:25 Pradeep RajashekarPradeep Rajashekar 5752 gold badges9 silver badges18 bronze badges 3- 1 What is the logic? Is it by position or key value? – Mamun Commented Nov 22, 2017 at 5:26
-
arr.filter(({ a }) => a !== 0)
? – Andrew Li Commented Nov 22, 2017 at 5:27 - 1 Possible duplicate of How do I remove an object from an array with JavaScript? – Rajesh Commented Nov 22, 2017 at 5:33
4 Answers
Reset to default 9You 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}]
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./docs/4.17.4#filter
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/7z5n5ure/
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)
}