I have two different sets of array of objects.
arr1 = [ {name: 'abcd', class: 'ef', pattern:'ds'}, {name: 'wdw', class: 'ef', pattern:'123'}, {name: 'wdd', class: 'ef', pattern:'d12sasds'}, {name: 'wdwd', class: 'a', pattern:'sd'}, {name: 'abcd', class: 'ef', pattern:'ds'}, {name: 'wdw', class: 'ef', pattern:'123'}, {name: 'wdd', class: 'ef', pattern:'d12sasds'}, {name: 'wdwd', class: 'a', pattern:'sd'}, ]
and
arr2 = [ {height: '123', weight:'12'}, {height: '123', weight:'12'}, ]
I want to combine these two array and put every element from the arr2 into arr1 on the third position..
so my new array looks like
newarr = [ {name: 'abcd', class: 'ef', pattern:'ds'}, {name: 'wdw', class: 'ef', pattern:'123'}, {name: 'wdd', class: 'ef', pattern:'d12sasds'}, {height: '123', weight:'12'}, {name: 'wdwd', class: 'a', pattern:'sd'}, {name: 'abcd', class: 'ef', pattern:'ds'}, {name: 'wdw', class: 'ef', pattern:'123'}, {height: '123', weight:'12'}, {name: 'wdd', class: 'ef', pattern:'d12sasds'}, {name: 'wdwd', class: 'a', pattern:'sd'}, ]
Advertisement
Answer
function a(arr1,arr2){ let arr3 = []; let i,n i = 0; n = 0; while (i < arr1.length) { if(i != 0 && String(i/3).split(".").length == 1 && n < arr2.length){ arr3[arr3.length] = arr2[n]; n++; } arr3[arr3.length] = arr1[i]; i++; } return arr3; } arr1 = [ {name: 'abcd', class: 'ef', pattern:'ds'}, {name: 'wdw', class: 'ef', pattern:'123'}, {name: 'wdd', class: 'ef', pattern:'d12sasds'}, {name: 'wdwd', class: 'a', pattern:'sd'}, {name: 'abcd', class: 'ef', pattern:'ds'}, {name: 'wdw', class: 'ef', pattern:'123'}, {name: 'wdd', class: 'ef', pattern:'d12sasds'}, {name: 'wdwd', class: 'a', pattern:'sd'} ]; arr2 = [ {height: '123', weight:'12'}, {height: '123', weight:'12'} ]; console.log(a(arr1,arr2));