简体   繁体   中英

Remove elements from array using spread

I have an array of animals arr = ['cat','dog','elephant','lion','tiger','mouse']

I want to write a function remove(['dog','lion']) which can remove the elements from arr, can we write this function using es6 spread?

example:

arr = ['cat','dog','elephant','lion','tiger','mouse']
remove(['cat', 'lion'])

arr should get changed to

arr = ['dog','elephant','tiger','mouse']

Note: I don't want mutations, so please don't suggest solutions that mutates array.

No, you can't, because they're not next to each other. There's been some discussion of taking spread and rest syntax further, but even in those discussions, I don't think a series of discontiguous selections would be possible.

I think the closest you can get is to call out the first few specifically and then use rest syntax for everything after 'lion' :

 const arr = ['cat','dog','elephant','lion','tiger','mouse']; const arr2 = [arr[1], arr[2], ...arr.slice(4)]; console.log(arr2);

...which I'm sure isn't what you wanted to do. :-)

From what I understand you're looking for a function that has its argument defined using the spread syntax. Here is an example:

 var arr = ['cat','dog','elephant','lion','tiger','mouse']; function remove(...toRemove){ toRemove.forEach(item => { var index = arr.indexOf(item); if(index != -1){ arr.splice(index, 1); } }) } remove('dog', 'lion'); // OR remove(...['dog', 'lion']); console.log(arr);

This is actually changing the original array (it mutates it) you've mentioned that you're not looking for mutation but you've also mentioned this arr should get changed to...

You can use spread if you want to pass lots of strings like remove('lion', 'dog') . Otherwise I don't think spread can help you.

You could take an iterator and exclude the values from iteration with spread operator.

Btw, it is not really advisable.

 function remove(array, items) { array[Symbol.iterator] = function* () { for (let value of Object.values(this)) { if (!items.includes(value)) { yield value; } } }; } var array = ['cat', 'dog', 'elephant', 'lion', 'tiger', 'mouse']; remove(array, ['dog', 'lion']); console.log([...array]); console.log(array);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

I don't understand the selected answer

const items = ['cat', 'dog', 'elephant', 'lion', 'tiger', 'mouse']
const valuesToRemove = ['dog', 'lion']
const filteredItems = items.filter(item => !valuesToRemove.includes(item))

you can use the array.filter method, it will return array with filtered values,

var filterMe = ["cat", "dog", "elephant", "lion", "tiger", "mouse"];
var answer = filterMe.filter((item) => item !== "dog")
                     .filter((item) => item !== "lion");
console.log(answer);

Similar to the previous filter solution, but using a regular expression. Beneficial if the remove array is large...

 let arr = ['cat', 'dog', 'elephant', 'lion', 'tiger', 'mouse']; const removeArr = ['cat', 'lion']; const removeRegExp = new RegExp(removeArr.join('|')); arr = arr.filter(e => !removeRegExp.test(e)); console.log(arr);

If you're using Typescript, you can also use the Omit utility type to remove specific keys from you object/ array.

Assuming an interface like this

interface Todo {
  title: string;
  description: string; // <--- assuming you want to omit `description` key
  completed: boolean;
  createdAt: number;
}
 
type TodoPreview = Omit<Todo, "description">;

the TodoPreview type will now expect an object with the other members included but with decription omitted

This will now be correct

const todo: TodoPreview = {
  title: "Clean room",
  completed: false,
  createdAt: 1615544252770,
};

This will ERROR out

const todo: TodoPreview = {
  title: "Clean room",
  completed: false,
  description: 'this should not be here' // <--- TS compiler will complain
  createdAt: 1615544252770,
};

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