Removing elements in an array [closed]

Posted on

Problem

I have a piece of code where I compare two arrays for similar values, then remove the similar values from one of the arrays. Is there a better way of writing this piece of code?

UpdateAddedTasksAfterDelete() {
    var tasksToRemove = [];
    var updatedTasks = [];

    for (var i = 0; i < this.deletedTasks.length; i++) {
        if (this.addedTasks.indexOf(this.deletedTasks[i]) > -1) { tasksToRemove.push(this.deletedTasks[i]); }
    }

    for (var i = 0; i < this.addedTasks.length; i++) {
        if (this.addedTasks.indexOf(tasksToRemove[i]) == -1) { updatedTasks.push(this.addedTasks[i]); }
    }

    this.addedTasks = updatedTasks;
}

Solution

I’m a little unclear as to what your goal is here, but here are a few options, depending on which outcome you are hoping for…

If your goal is to take two arrays, combine them, and discard any duplicate values, using a Set will automatically discard the values that appear more than once for you.

Simply use:

var mySet = new Set(array1)
array2.forEach((item)=>{mySet.add(item)});

Then convert the set back to an array if you need it specifically in array form, using the spread operator:

var finalArray = [...mySet]

‘finalArray’ will now hold each unique value from the combination of your two original arrays.

If your goal is to compare two arrays, removing values from the first array that are present in the second, use filter:

var finalArray = array1.filter((item)=>{return !array2.includes(item)})

‘finalArray’ will now hold all values of array1 that do not also exist in array2.

Leave a Reply

Your email address will not be published. Required fields are marked *