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

2

2 Answers 2

8

You can use .filter

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

// should give you [{id: 1, name: 'a'}]
Sign up to request clarification or add additional context in comments.

4 Comments

I see, perhaps this answer might be helpful to you then: stackoverflow.com/questions/9882284/…
I did an edit request and all you had to do was replace the variable a with the new array
first time I see the use of the "~" in a context like this, can you explain what it does?
@Fabrice see here for an explanation, but I answered this question many years ago, now I would recommend using Array.includes
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.

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.