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?

3
  • 1
    What is the logic? Is it by position or key value? Commented Nov 22, 2017 at 5:26
  • arr.filter(({ a }) => a !== 0)? Commented Nov 22, 2017 at 5:27
  • 1
    Possible duplicate of How do I remove an object from an array with JavaScript? Commented Nov 22, 2017 at 5:33

4 Answers 4

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}]
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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/

Comments

-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)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.