UI_Dev
UI_Dev

Reputation: 3427

Iterate array of objects and split as array for every two objects in javascript

I have a scenario to achieve the below output (attached at last) dynamically by iterating over array.

Original Array:

var original = [{
        image: 'sampleImage1.jpg',
        alignment: 'center',
        width: 200,
        height: 200,
        margin: [0, 20, 0, 20]
    },
    {
        image: 'sampleImage2.jpg',
        alignment: 'center',
        width: 200,
        height: 200,
        margin: [0, 20, 0, 20]
    },
    {
        image: 'sampleImage3.jpg',
        alignment: 'center',
        width: 200,
        height: 200,
        margin: [0, 20, 0, 20]
    },
    {
        image: 'sampleImage4.jpg',
        alignment: 'center',
        width: 200,
        height: 200,
        margin: [0, 20, 0, 20]
    }
    ];
    
   var arr1 = [];
 for(var i = 0; i < original.length; i += 2) {
        arr1.push(original.slice(i, i + 2));
    }
    
    console.log(arr1);

I need to convert every two objects as array and in between every two arrays, I need to insert below two arrays (static one which will insert after every two arrays)

["name1", "nm1"],
[{ text: "", border: [false, false, false, false], fillColor: "white" }, { text: "", border: [false, false, false, false], fillColor: "white" }],

Output

var output = [
    [
        {
            image: 'sampleImage.jpg',
            alignment: 'center',
            width: 200,
            height: 200,
            margin: [0, 20, 0, 20]
        },
        {
            image: 'sampleImage.jpg',
            alignment: 'center',
            width: 200,
            height: 200,
            margin: [0, 20, 0, 20]
        }
    ],
    ["name1", "nm1"],  // ["a", "b"]
    [{ text: "", border: [false, false, false, false], fillColor: "white" }, { text: "", border: [false, false, false, false], fillColor: "white" }],
    [
        {
            image: 'sampleImage.jpg',
            alignment: 'center',
            width: 200,
            height: 200,
            margin: [0, 20, 0, 20]
        },
        {
            image: 'sampleImage.jpg',
            alignment: 'center',
            width: 200,
            height: 200,
            margin: [0, 20, 0, 20]
        }
    ],
    ["name2", "nm2"],   // ["c", "d"]
    [{ text: "", border: [false, false, false, false], fillColor: "white" }, { text: "", border: [false, false, false, false], fillColor: "white" }],
]

Also, at last I have an array

var captions = ["a", "b", "c", "d"] 

(based on original array length. Is it possible to add these values instead of name1, nm1 (static content) ? Means a - refers to first item, b- refers to second item

I'm stuck how to achieve this logic. Any help would be highly appreciated. Need solution only in javascript.

Upvotes: 0

Views: 622

Answers (3)

Noor Ul Ain
Noor Ul Ain

Reputation: 600

is that how you want?

var original = [{ image: 'sampleImage1.jpg', alignment: 'center', width: 200, height: 200, margin: [0, 20, 0, 20] }, { image: 'sampleImage2.jpg', alignment: 'center', width: 200, height: 200, margin: [0, 20, 0, 20] }, { image: 'sampleImage3.jpg', alignment: 'center', width: 200, height: 200, margin: [0, 20, 0, 20] }, { image: 'sampleImage4.jpg', alignment: 'center', width: 200, height: 200, margin: [0, 20, 0, 20] } ];
let captions = ['a','b','c','d'];
let arr1 = ["name1", "nm1"]
let arr2 = [{ text: "", border: [false, false, false, false], fillColor: "white" }, { text: "", border: [false, false, false, false], fillColor: "white" }]
let result = []
let tempSubArr = []

original.forEach((value,index)=>{
    
    if(index%2 != 0) {
        result.push(tempSubArr,[captions[index-1],captions[index]],arr2)
        counter = 0
        tempSubArr = []
    }
    tempSubArr.push(value)
})

Upvotes: 0

Terry Lennox
Terry Lennox

Reputation: 30685

You can use Array.reduce() to get the desired result, inserting the two extra arrays every two rows. We also include the captions array, adding two elements each time.

var original = [{ image: 'sampleImage1.jpg', alignment: 'center', width: 200, height: 200, margin: [0, 20, 0, 20] }, { image: 'sampleImage2.jpg', alignment: 'center', width: 200, height: 200, margin: [0, 20, 0, 20] }, { image: 'sampleImage3.jpg', alignment: 'center', width: 200, height: 200, margin: [0, 20, 0, 20] }, { image: 'sampleImage4.jpg', alignment: 'center', width: 200, height: 200, margin: [0, 20, 0, 20] } ];
    
let captions = ['a','b','c','d'];
let insert = [ { text: "", border: [false, false, false, false], fillColor: "white" }, { text: "", border: [false, false, false, false], fillColor: "white" }];

let result = original.reduce((acc, cur, idx) => { 
    if ((idx % 2 === 0)) {
        acc.push([cur]);
    } else {
        acc[acc.length - 1].push(cur);
        acc.push(captions.slice(idx - 1, idx + 1));
        acc.push(insert);
    }
    return acc;
}, [])


console.log('Result:', JSON.stringify(result, null, 2));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 1

loop
loop

Reputation: 973

Would this do? We iterate half the length of the original array and pick two items on each iteration. We also add the static content at the end on each iteration.

var original = [{
        image: 'sampleImage1.jpg',
        alignment: 'center',
        width: 200,
        height: 200,
        margin: [0, 20, 0, 20]
    },
    {
        image: 'sampleImage2.jpg',
        alignment: 'center',
        width: 200,
        height: 200,
        margin: [0, 20, 0, 20]
    },
    {
        image: 'sampleImage3.jpg',
        alignment: 'center',
        width: 200,
        height: 200,
        margin: [0, 20, 0, 20]
    },
    {
        image: 'sampleImage4.jpg',
        alignment: 'center',
        width: 200,
        height: 200,
        margin: [0, 20, 0, 20]
    }
    ];

const staticContent = [
  ["name1", "nm1"],
  [{ text: "", border: [false, false, false, false], fillColor: "white" }, { text: "", border: [false, false, false, false], fillColor: "white" }],
];

const result = [];

for(let i=0;i<original.length/2;i++) {
  result.push([ original[i*2], original[i*2+1] ].filter(v=>v));
  result.push(...staticContent);
}

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 1

Related Questions