简体   繁体   中英

javascript Delete from array between 2 indices

With an array of: [1, 2, 3, 4, 5, 6]

I would like to delete between 2 indices such as 2 and 4 to produce [1, 2, null, null, 5, 6] . What's the easiest way to do this?

Hopefully better than this:

const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
let i = 2;
const rangeEnd = 9;
while (i < rangeEnd) {
  delete array[i];
  i++;
}

console.log(array)

If you want to use some native API you can actually do this with splice() . Otherwise, you should iterate a for loop through your array and change the value in each iteration.

Here is an example of how it would be done:

 const array = [1, 2, 3, 4, 5, 6] array.splice(3, 2, null, null) // the First element is beginning index and the second is count one will indicate how many indexes you need to traverse from the first one, then you should provide replace element for each of them. console.log(array)

Note: For more info about it you can read more here .

There is a possible workaround for large scale replacement, so I will give it a touch here:

 var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; var anotherArr = Array(2).fill(null); // or you can simply define [null, null, ...] Array.prototype.splice.apply(arr, [3, anotherArr.length].concat(anotherArr)); console.log(arr);

As you mean the range (2, 4] so you can follow this: The range is: lower limit exclusive and the upper limit inclusive.

 const arr = [1, 2, 3, 4, 5, 6]; const deleteRange = (arr, f, t) => { return arr.map((item, i) => { if (i + 1 > f && i + 1 <= t) { return null; } return item; }) } console.log(deleteRange(arr, 2, 4));

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