0

I want to delete elements from array in array (can't remember how it is named in math), for example:

var arr1 = ['uno', 'dos', 'tres', 'cuatro'],
    arr2 = ['dos', 'cuatro'],
    arr3 = arr1.without(arr2);
//arr3 === ['uno', 'tres']

Greetings

5
  • It's named as matrix in math Commented Apr 13, 2017 at 10:31
  • arr3 = arr1.filter( item => !arr2.includes(item) ) Commented Apr 13, 2017 at 10:31
  • I think this kinda duplicate of this Commented Apr 13, 2017 at 10:32
  • Check this. stackoverflow.com/questions/19957348/… Commented Apr 13, 2017 at 10:33
  • I think the math term that you are looking for is called 'set difference'. Commented Apr 13, 2017 at 10:57

4 Answers 4

3

Array#filter may be helpful.

var arr1 = ['uno', 'dos', 'tres', 'cuatro'],
    arr2 = ['dos', 'cuatro'],
    arr3 = arr1.filter(v => arr2.indexOf(v) == -1);
    
    console.log(arr3);

Sign up to request clarification or add additional context in comments.

2 Comments

I hoped there is some native function for it, but thanks!
@JimiAlvaro Native function? Array#filter is definetely native (:
2

var arr1 = ['uno', 'dos', 'tres', 'cuatro'];
var arr2 = ['dos', 'cuatro'];

arr1 = arr1.filter(function(item){
  return arr2.indexOf(item) < 0;
});
console.log(arr1)

Comments

0

You could use Array#includes and take the negated result.

var arr1 = ['uno', 'dos', 'tres', 'cuatro'],
    arr2 = ['dos', 'cuatro'],
    arr3 = arr1.filter(v => !arr2.includes(v));
    
console.log(arr3);

Comments

0

Here you are, a ready function for that:

function substractArrays (arr1, arr2) {
    if (arr2.length) {
      return arr1.filter(item => {
        return !arr2.some(elem => {
          return item.id === elem.id;
        });
      });
    } else {
      return arr1;
    }
}

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.