How to insert specific index in array using lodash?
Currently lodash not have that. You can use this alternate
arr.splice(index, 0, item);
const arr = [
{name: 'john'},
{name: 'jane'},
{name: 'saske'},
{name: 'jake'},
{name: 'baki'}
]
arr.splice(2, 0, {name: 'ace'})
console.log(arr)
There is no support of such functionality in lodash : see issue.
If you still want it to look like done with lodash, then you can do it like this way.
fields = [{name: 'john'},
{name: 'jane'},
{name: 'saske'},
{name: 'jake'},
{name: 'baki'}
];
_.insert = function (arr, index, item) {
arr.splice(index, 0, item);
};
_.insert(fields,2,{'name':'ace'});
console.log(fields);
You can try something like this:
const arr = [{
name: 'john'
},
{
name: 'jane'
},
{
name: 'saske'
},
{
name: 'jake'
},
{
name: 'baki'
}
]
const insert = (arr, index, newItem) => [
...arr.slice(0, index),
newItem,
...arr.slice(index)
];
const newArr = insert(arr, 2, {
name: 'ace'
});
console.log(newArr);