1

I have an array array1 = [1,2,3,4,5,6] and another array array2 = [4,5].

The objective is to remove array2's elements from array1 with the least time complexity.

Final array is [1,2,3,6]

I know we can do something like this for every element

function remove(array, element) {
    return array.filter(e => e !== element);
}

let array1 = [1,2,3,4,5,6];
array2 = [4,5];
array2.forEach(el => {
    array1 = remove(array1, el);
});

How do i make it better?

3
  • 1
    Is this from an academic perspective, or is this just a problem you've got to solve as part of your work? Lodash is full of tools that can help with this if you're just trying to get this functionality into your application. Commented Sep 5, 2018 at 16:04
  • This is geometrically slow since it requires M x N passes. A faster solution involves sorting both arrays so you step through each of them once, but if order matters, that isn't a valid solution. Commented Sep 5, 2018 at 16:05
  • It's for academic purposes but the goal is to make it into a class and create a package of tools Commented Sep 6, 2018 at 5:59

2 Answers 2

2

I have two solutions for you :

var arr1 = [ 1, 2,3 ];
var arr2 = [1,2,4 ];
var result = arr1.filter(o1 => arr2.filter(o2 => o2 === o1).length === 0);
console.log(result);

Or you can use difference of Loadash

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

Comments

2

Simpler and cleaner

const arr1 = [1,2,3,4]
const arr2 = [3,4]
const newArray = arr1.filter( x => !arr2.includes(x))
console.log(newArray)

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.