Wednesday, 10 January 2018

javascript - How to insert specific index in array using lodash?





I already see the lodash documentation but I don't know what
function do I need to use to solve my problem. I have
array



const arr = [

{name: 'john'},
{name: 'jane'},
{name: 'saske'},
{name:
'jake'},
{name: 'baki'}

]



I
want to add {name: 'ace'} before saske. I know about splice in
javascript, but I want to know if this is possible in lodash.



Answer




You can try something like
this:



/>

data-console="true" data-babel="false">
class="snippet-code">

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);






No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...