简体   繁体   中英

How to remove n from an array without mutating it?

嗨,这个问题需要删除

You could use filter or reduce , or copy the array first by using slice , and then perform splice .

Personally, I like filter for its simplicity, and clear intention

filter

 function removeItem(array, n) { return array.filter((elem, i) => i !== n); } const original = [1,2,3,4]; console.log(removeItem(original, 1)); console.log(original); 

reduce

 function removeItem (array, n) { return array.reduce((result, elem, i) => { if (i !== n) result.push(elem); return result; }, []) } const original = [1,2,3,4]; console.log(removeItem(original, 1)); console.log(original); 

slice and splice

 function removeItem(array, n) { const result = array.slice(); result.splice(n, 1); return result; } const original = [1,2,3,4]; console.log(removeItem(original, 1)); console.log(original); 

Performance Test

https://jsperf.com/so53833297

Documentation

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

function removeItem(array, n) {
    return array.filter((x, i) => i != n)
}

 var array = [2,1,3,5,6,8,9,7]; function removeArray(array,n){ array.splice(array.indexOf(n),1); return array; } console.log(array); array = removeArray(array, 6); console.log(array); 

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