0

I want to delete the numbers in an array from the original array if each element in compared using ES6 standards

const numbers = [1,4,2,3,54];
const output = except(numbers,[1,54]);

Where except is a function that expects an array (original one) and the numbers user wants to remove

3 Answers3

0

This is how i achieved this, obviously there are better implementations or simpler ones

function except(array,excluded) {
    console.log(array.filter((item) => excluded.indexOf(item) === -1));   
}

the function except expects the original array and the values user wants to remove, according to MDN filter method creates a new array with all elements that pass the test implemented by the provided function.

In our case the provided function is the indexOf(item) , where -1 means if not equal to, so the filter function is filtering values after removing those that are in excluded array. So the output we see is:

Array(3) [ 4, 2, 3 ]

0
function except(array, excludes) {
  return array.filter((item) => ! excludes.includes(item));
}

You can also use the new ES6 syntax Array.prototype.includes if that's what you are after.

DAMIEN JIANG
  • 573
  • 4
  • 16
0

the same could be achieved by a simpler implementation using this code:


function except(array,excluded){
    const output=[];

    for(let element of array)
    if(!excluded.includes(element))
        output.push(element);
    return output;
    
        }

console.log(output);  

Where the function expects same parameters as arguments, we are using the for-of-Loop which traverses elements of the array, the if statement here basically means those elements from the original array that are NOT in the array excluded should be appended (pushed) to the output array.

At the end we didn't use 'else or else if' because all values that weren't in the array will be present by then in the output array and control won't execute whatever in the if block any more

We get the same output:

Array(3) [ 4, 2, 3 ]