javascriptlodash

How can I insert a specific index in an array using Lodash?


I already see the Lodash documentation, but what function do I need to use to solve my problem? I have an 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.


Solution

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