I am working on a react component. Requirement is to add a new object at alternate position within array of object eg 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?
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);
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);
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.