1

I have an array of objects that looks like this

[
  { id: 1, state: 'PURCHASED' },
  { id: 2, state: 'PURCHASED' },
  { id: 3, state: 'SOLD' },
  { id: 1, state: 'SOLD' },
  { id: 4, state: 'PURCHASED' },
  { id: 6, state: 'SOLD' },
  { id: 9, state: 'PURCHASED' }
]

I would like to filter this array such that I get the items which were PURCHASED but never SOLD. The out would look something like this

[
  { id: 2, state: 'PURCHASED' },
  { id: 3, state: 'SOLD' },
  { id: 4, state: 'PURCHASED' },
  { id: 6, state: 'SOLD' },
  { id: 9, state: 'PURCHASED' }
]
A-D
  • 371
  • 1
  • 9
  • 24
  • 1. [Group](https://stackoverflow.com/questions/40774697/how-to-group-an-array-of-objects-by-key) the array by `id` 2. [Filter](https://stackoverflow.com/questions/2722159/how-to-filter-object-array-based-on-attributes) the resulting composite objects. 3. (I guess optional): Ungroup the result using [`.map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) or [`.flatMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap). – VLAZ Feb 10 '20 at 12:42

1 Answers1

1

You could find the index by looking for same id and if exist, delete this item.

var data = [{ id: 1, state: 'PURCHASED' }, { id: 2, state: 'PURCHASED' }, { id: 3, state: 'SOLD' }, { id: 1, state: 'SOLD' }, { id: 4, state: 'PURCHASED' }, { id: 6, state: 'SOLD' }, { id: 9, state: 'PURCHASED' }],
    result = data.reduce((r, o) => {
        var index = r.findIndex(q => o.id === q.id);
        if (index === -1) r.push(o);
        else r.splice(index, 1);
        return r;
    }, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392