0

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.

2
  • Could this be of any help? stackoverflow.com/questions/35656677/… Commented Oct 28, 2021 at 9:06
  • 1
    @loop you can see the code snippet for my attempt. Commented Oct 28, 2021 at 9:16

3 Answers 3

1

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

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

7 Comments

Thanks for your hint, but array[0] should have two objects. but above one is different. Can you please refer the output one ?
Thanks for checking my answer, I've updated to correct, the output should be as expected now.
Thanks Terry, it worked. And one more thing, 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
Oh sure, could you update the question to include this, along with the expected result? Thank you!
Updated my question and output to include this one
|
1

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

4 Comments

Thanks @loop, this one is breaking if we have 5 array of objects (original)
You mean if the original array has an odd number of items? Right. The behavior is undefined in that case. How it should behave?
it shouldn't show as undefined. just one item in that last array. And one more thing, 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 added a filter which removes any empty values. I think I will not go further into feature development.
0

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

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.