Recently I recently came across these two solution to replace an item at a specific index in an array, but I'm wondering, which one are better and why?
function replace(array, index, item) {
const newArray = [...array];
newArray[index] = item;
return newArray;
}
function replace(array, index, item) {
return [
...array.slice(0, index),
item,
...array.slice(index + 1)
];
}
Both functions do exactly the same thing. They both don't modify original array (no mutation) and the only difference is first one simply shallow clone the array before modifying specified index, and second one shallow clone all items before specified index, inserting new value at the specified index and shallow clone the rest of the items.
The first function is better because its 33% faster, since it does the modification in 2 steps vs 3 steps in second function.
If mutation is not an issue, even faster function can be used:
function replace(array, index, item) {
return array[index] = item;
}
"better" can be subjective. There are several factors you may consider. Some of these:
You could also add this version to your list of possible implementations, which is more like the first version:
function replace(array, index, item) {
return Object.assign([], array, { [index]: item });
}
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.