16

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.

user3818576
  • 2,979
  • 8
  • 37
  • 62
  • 2
    Please read this thread, you'll have idea. https://github.com/lodash/lodash/issues/89 – ravi Mar 20 '19 at 05:49
  • 4
    Possible duplicate of [How to insert an item into an array at a specific index (JavaScript)?](https://stackoverflow.com/questions/586182/how-to-insert-an-item-into-an-array-at-a-specific-index-javascript) and [JS insert into array at specific index](https://stackoverflow.com/questions/32024319) – adiga Mar 20 '19 at 07:36

3 Answers3

21

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)
User863
  • 19,346
  • 2
  • 17
  • 41
6

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);
Kunal Mukherjee
  • 5,775
  • 3
  • 25
  • 53
1

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);
ravi
  • 1,130
  • 16
  • 29