Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert specific index in array using lodash? [duplicate]

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.

like image 377
user3818576 Avatar asked Mar 20 '19 05:03

user3818576


2 Answers

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)
like image 97
User863 Avatar answered Oct 05 '22 15:10

User863


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);
like image 43
ravi Avatar answered Oct 05 '22 14:10

ravi