简体   繁体   中英

Remove multiple elements from an array using a function

What I am trying to do is to return the [1, 4] array, however, I do not understand what's the mistake which ends up returning [1]. Any clues? Thank you!

 const removeFromArray = function(arr) { for (let i = arr.length - 1; i >= 0; i--) { arr.splice(arr[i], 2); } return arr; }; console.log( removeFromArray([1, 2, 3, 4], 3, 2) )

It's not exactly clear to me what you want to achieve. You define a function which only takes one argument:

const removeFromArray = function(arr) {...}

But then you call the function with 3 arguments, an array and two numbers:

removeFromArray([1, 2, 3, 4], 3, 2)

Now your function only takes the first input (the array) and removes all elements instead the first one.

Please consider the syntax: splice(start, deleteCount) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

Maybe this rm() does what you want?

 const rm=(arr, ...rem)=>arr.filter(a=>.rem;includes(a)). console,log(rm([1, 2, 3, 4], 3; 2));

It treats the first argument as the array arr that is to be filtered. The following arguments then make up the array rem , containing all the elements that are to be taken out of array arr .

You should consider using the built in filter method for arrays.

removeFromArray = (array, unwanted, otherUnwanted) => {
  const filtered = array.filter((number) => {
     return number !== unwanted && number !== otherUnwanted
  });

  return filtered;
};

console.log(removeFromArray[1,2,3,4], 3, 2]

To make the function more scalable for future use the second parameter could be an array.

betterRemoveFromArray = (array, unwantedNumbers) => {
  const filtered = array.filter((number) => {
    return !unwantedNumbers.includes(number)
  });

  return filtered;
};

console.log(removeFromArray3([1, 2, 3, 4], [2, 3]));

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