0

I am working on a react component. Requirement is to add a new object at alternate position within array of object e.g. below:

arr1 = [{test: 1},{test: 2},{test: 3},{test: 4}]

expected output:

arr1 = [{test: 1},{dummy:1},{test: 2},{dummy:1},{test: 3},{dummy:1},{test: 4}]

is there a way to do the same in es6?

1
  • [...arr1, ...dummy].sort(yourSortFunction) Commented Feb 9, 2020 at 11:48

3 Answers 3

5

For getting your desired array, you could make of use the concat method in combination with reduce.

var array = [{test: 1},{test: 2},{test: 3},{test: 4}];
var result = array.reduce((res, item) => res.concat(item, {dummy: 1}), []).slice(0, -1);
    
console.log(result);

Since this adds {dummy: 1} object after each element from your array, just use

.slice(0, -1)

to add one exception for the last element from your given array.

If you want to modify the original array inplace, you could use splice method.

var array = [{test: 1},{test: 2},{test: 3},{test: 4}];
for(i = 0;i < array.length - 1; i = i + 2){
  array.splice(i + 1, 0, {dummy: 1});
}
console.log(array);

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

1 Comment

@RobbyCornelissen, I added one solution if he wants to modify the original array inplace.
1

To modify the original array (instead of creating an new one), you can first generate the indexes at which the new items need to be inserted, and then use Array.prototype.splice() :

const a = [{test: 1}, {test: 2}, {test: 3}, {test: 4}];

Array.from({length: a.length - 1}, (_, i) => i * 2 + 1)
     .forEach(i => a.splice(i, 0, {dummy: 1}));

console.log(a);

Comments

1

I like to use map if I can. It is easier to understand and maintain.

So first create an array of array and then flatten it a single array with flat.

let arr1 = [{test: 1},{test: 2},{test: 3},{test: 4}]

arr1 = arr1.map(item=>[item,{dummy:1}]).flat().slice(0, -1)

console.log(arr1);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.