-1

I need to remove all array members that are not based on property given, here is example I have something like this

    const idToStay = 1;

    const objList = [{
        id: 1,
        name: 'aaa',
      },
      {
        id: 4,
        name: 'bbb',
      },
      {
        id: 7,
        name: 'ccc',
      },
    ];

I need to remove all others objects that does not have id with number 1, I know how to remove but how to stay and remove all others

Here I can remove like this

const filteredObjList = objList.filter(x => !idsToRemove.includes(x.id));

console.log(filteredObjList);
Miomir Dancevic
  • 6,726
  • 15
  • 74
  • 142
  • `but how to stay and remove all others` invert the filter? – 0stone0 Apr 05 '22 at 09:09
  • Does this answer your question? [How to filter object array based on attributes?](https://stackoverflow.com/questions/2722159/how-to-filter-object-array-based-on-attributes) – 0stone0 Apr 05 '22 at 09:10

3 Answers3

2

It's the same thing, just without the exclamation mark

const idToStay = 1;

const objList = [{
        id: 1,
        name: 'aaa',
      },
      {
        id: 4,
        name: 'bbb',
      },
      {
        id: 7,
        name: 'ccc',
      },
    ];
    
    
const filteredObjList = objList.filter(x => idToStay === x.id);

console.log(filteredObjList);
user3133
  • 592
  • 4
  • 12
0

I hope this works for you.

    var filtered = objList.filter(function(el) { return el.id === 1; });
    console.log(filtered);

Thanks, Mark it as answer if it works.

0

const objList = [
      {
        id: 1,
        name: 'aaa',
      },
      {
        id: 2,
        name: 'bbb',
      },
      {
        id: 3,
        name: 'ccc',
      },
    ];
    
var filtered = objList.filter((el) => el.id === 3 );
console.log(filtered);