简体   繁体   中英

Javascript Remove an array element and reorder the remaining elements

I have an array with a fixed length of 6.

I want to remove the first element from the array, then shift all the elements left by 1, but the length of the array should remain as 6 (the 6th position of the array can be undefined)

I tried using splice but the array length was reduced to 5 which is not what I want to happen.

What is the best approach to achieve the above?

You can use Array.prototype.slice (which does not mutate the original array unlike splice ) to take a copy of the array from the 1st position.

Then use Array.from to get a new array from the copy and mention the length property value of the old array:

 const arr = [1, 2, 3, 4, 5, 6] const newArr = Array.from({length: arr.length, ...arr.slice(1)}); console.log(newArr);

You can shift the first element, then push undefined , as shown below:

 const array = [1, 2, 3, 4, 5, 6] array.shift() array.push(undefined) console.log(array)

You can use the delete operator. It will remove the item, and replace it with undefined, making sure the length does not change. You can then sort the array, to move the undefined element to the end:

 const arr = [1, 2, 3, 4, 5, 6] delete arr[0] console.log(arr.sort((a, b) => a === undefined? 1: 0))

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