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.

2

3 Answers 3

23

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect one-liner
7

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

Comments

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

1 Comment

Insert is on way to be supported in lodash: github.com/lodash/lodash/pull/4567

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.