Is there any function which inserts value at certain index and returns modified array like filter
or map
?
I already tried array.splice(item, 0, index)
but it returns []
instead of modified array
Is there any function which inserts value at certain index and returns modified array like filter
or map
?
I already tried array.splice(item, 0, index)
but it returns []
instead of modified array
You could add a value at an index by returning two values at an index with Array#flatMap
const
array = [1, 2, 4, 5],
index = 2,
newValue = 3,
newArray = array.flatMap((v, i) => i === index ? [newValue, v] : v);
console.log(...newArray);
No, but you can add your own function using Array.prototype
:
const arr = ["foo", "bar", "baz"]
Array.prototype.spliceReturn = function(idx, val) {
this.splice(idx, 0, val)
return this
}
let res = arr.spliceReturn(1, 'biz')
console.log(res)
You can add to the array using splice
and return it:
const insert = (arr, index, val) => {
arr.splice(index, 0, val);
return arr;
}
console.log( insert([0,1,3], 2, 2) );
The next approach handles array items more flexible, be it just a single item or even multiple ones. It meets both acceptance criteria, the one of the OP and the one of ASDFGerte ...
function newArrayFromInsertItems(arr, idx, ...items) {
arr = Array.from(arr ?? []);
arr.splice(idx, 0, ...items);
return arr;
}
const arr = ['foo', 'bar', 'baz'];
console.log(
"newArrayFromInsertItems(arr, 1, 'buz') ...",
newArrayFromInsertItems(arr, 1, 'buz')
);
console.log(
"newArrayFromInsertItems(arr, 1, 'biz', 'buz') ...",
newArrayFromInsertItems(arr, 1, 'biz', 'buz')
);
console.log(
"newArrayFromInsertItems(arr, 2, ['bar', 'baz'], 'biz') ...",
newArrayFromInsertItems(arr, 2, ['bar', 'baz'], 'biz')
);
console.log('arr ...', arr);
.as-console-wrapper { min-height: 100%!important; top: 0; }
[1, 2, 4].toSpliced(2, 0, 3) // returns a new array, [1, 2, 3, 4].
Check out the documentation for Array.prototype.toSpliced().