6

I have two arrays:

array a:

var a = [
  {
    id: 1,
    name: 'a'
  },
  {
    id: 2,
    name: 'b'
  },
  {
    id: 3,
    name: 'c'
  }
];

array ids:

var ids = [1];

I want to array a filtered by array ids, result i wanted:

var a = [
  {
    id: 1,
    name: 'a'
  }
];

The most important thing is i want the change on the original array, rather than return a new array.

underscore solution is better:)

dhilt
  • 18,707
  • 8
  • 70
  • 85
huan feng
  • 7,307
  • 2
  • 32
  • 56
  • Side note: check out this META post http://meta.stackoverflow.com/questions/288160/no-thanks-damn-it – Alexei Levenkov May 09 '15 at 02:33
  • Unlike forum sites, we don't use "Thanks", or "Any help appreciated", or signatures on [so]. See "[Should 'Hi', 'thanks,' taglines, and salutations be removed from posts?](http://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-be-removed-from-posts). – John Saunders May 09 '15 at 02:39

2 Answers2

8

You can use .filter

a = a.filter(function(el){ 
    return ~ids.indexOf(el.id)
});

// should give you [{id: 1, name: 'a'}]
Edwin Reynoso
  • 1,511
  • 9
  • 18
bruchowski
  • 5,043
  • 7
  • 30
  • 46
  • 1
    I see, perhaps this answer might be helpful to you then: http://stackoverflow.com/questions/9882284/looping-through-array-and-removing-items-without-breaking-for-loop – bruchowski May 09 '15 at 02:41
  • I did an edit request and all you had to do was replace the variable a with the new array – Edwin Reynoso May 10 '15 at 01:29
  • first time I see the use of the "~" in a context like this, can you explain what it does? – Fabrice May 30 '19 at 01:47
  • 2
    @Fabrice see [here](https://wsvincent.com/javascript-tilde/) for an explanation, but I answered this question many years ago, now I would recommend using [Array.includes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes) – bruchowski May 30 '19 at 02:27
4

Today I tried to solve similar task (filtering the original array of objects without creating a new array) and this is what I came up with:

const a = [{ id: 1, name: 'a'}, { id: 2, name: 'b'}, { id: 3, name: 'c'}];
const ids = [1];

Array.from(Array(a.length).keys()).reverse().forEach(index =>
  !ids.some(id => id === a[index].id) && a.splice(index, 1)
);

console.log(a); // [{ id: 1, name: 'a'}]

The point is that we need to loop back through the original array to be able to use Array.prototype.splice, but I didn't want the for-loop, I wanted to have ES6 one-liner. And Array.from(Array(a.length).keys()).reverse() gives me a list of reversed indexes of the original array. Then I want to splice the original array by current index only if the corresponding item's id is not present in the ids array.

dhilt
  • 18,707
  • 8
  • 70
  • 85