2

I have an array

var arrIn = [
    { 'a': 'a-0', 'b': 'b-0', 'c': 'c-0' },
    { 'a': 'a-1', 'b': 'b-1', 'c': 'c-1' },
    { 'a': 'a-2', 'b': 'b-2', 'c': 'c-2' }
];

I need to remove the item arrIn.a === 'a-1' with lodash and have

var arrOut = [
    { 'a': 'a-0', 'b': 'b-0', 'c': 'c-0' },
    { 'a': 'a-2', 'b': 'b-2', 'c': 'c-2' }
];

How to do it with Lodash _.omit() or _.omitBy()?

Roman
  • 19,236
  • 15
  • 93
  • 97
  • 2
    You can also do this with just the standard [`array.filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter): `arrIn.filter(element => element.a !== 'a-1')` – Hamms Mar 15 '18 at 20:52

2 Answers2

3

A solution is not complicated, but sometimes it takes some time to find it. You are going to use _.omitBy() and then to transform the object into an array with Object.values():

var arrIn = [
    { 'a': 'a-0', 'b': 'b-0', 'c': 'c-0' },
    { 'a': 'a-1', 'b': 'b-1', 'c': 'c-1' },
    { 'a': 'a-2', 'b': 'b-2', 'c': 'c-2' }
];

var arrOut = _.omitBy(arrIn, {'a': 'a-1'});     
    arrOut = Object.values(arrOut);

console.info('_omit:',{arrIn: arrIn, arrOut:arrOut});

You have in console =>

[
    { 'a': 'a-0', 'b': 'b-0', 'c': 'c-0' },
    { 'a': 'a-2', 'b': 'b-2', 'c': 'c-2' }
];
Roman
  • 19,236
  • 15
  • 93
  • 97
2

With an array like this, you can also use the lodash _.filter method, or the native Array .filter method if available (not supported on older browsers).

Example of both:

var arrIn = [
    { 'a': 'a-0', 'b': 'b-0', 'c': 'c-0' },
    { 'a': 'a-1', 'b': 'b-1', 'c': 'c-1' },
    { 'a': 'a-2', 'b': 'b-2', 'c': 'c-2' }
];

// Using Lodash:
var lodashResult = _.filter(arrIn, function(item) { return item.a !== "a-1"; });
console.log("Lodash:", lodashResult);

// Using built-in filter method and es6 arrow syntax:
var filterResult = arrIn.filter(item => item.a !== "a-1");
console.log("Built-in filter:", filterResult);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.5/lodash.min.js"></script>
CRice
  • 29,968
  • 4
  • 57
  • 70