简体   繁体   中英

Removing elements from an array by value in Javascript

It's a bit fuzzy for me, but I'm trying to create a simple function that takes an array and some arguments and removes the arguments from the array.

For example if I have an array such as [1,2,3,4] and the arguments 2,3 it would return [1,4] as a result.

This is what I have so far:

const removeFromArray = (arr) => {
    let args = Array.from(arguments);

    return arr.filter(function (item) {
        !args.includes(item);
    });
}

It doesn't work though. It works if I want to remove all the items from the array, but doesn't if I only go for specific ones.

How can I make this work so that it works even if I'm supplying an argument that is not part of the array (I want it to ignore those) and also if I have strings in the array as well?

Thanks in advance!

You could take rest parameters ... for the items to exclude the values.

 const removeFromArray = (array, ...items) => array.filter(item => !items.includes(item)); console.log(removeFromArray([1, 2, 3, 4], 1, 4)) 

To use you style, you need to exclude the first item of arguments , because this is the array with all items.

let args = Array.from(arguments).slice(1);
//                              ^^^^^^^^^

In arrow functions the implicit object arguments doesn't exist, so declare the function using the keyword function , likewise, you need to return the result of the function includes within the handler of the function filter .

 const removeFromArray = function() { let [arr, ...args] = Array.from(arguments); return arr.filter(function (item) { return !args.includes(item); }); } console.log(removeFromArray([1,2,3,4], 2, 3)); 

Add a second parameter for the items you want to have removed.

const removeFromArray = (arr, toBeRemoved) => {
    return arr.filter(item => !toBeRemoved.includes(item));
}

Example call:

const array = [1, 2, 3, 4]
const newArray = removeFromArray(arr, [2, 3])
console.log(newArray) // [1, 4]

Stick it to the Array.prototype , might use it somewhere else

Array.prototype.remove = function(...args) {
  return this.filter(v => !args.includes(v));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM