Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Array Map Not Working on Replicated Arrays of Objects

Let’s take a simple Array of Objects.

let objarray = [
        {
            type: 2,
            number: 4768
        },
        {
            type: 2,
            number: 3168
        }
];

And perform a simple map function

objarray.map((elem, i) =>  {
        if (i == 0) {
            elem.number = 1;
        }
        else {
            elem.number = 0;
        }
});

The result works as expected.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

0 : {type: 2, number: 1}
1 : {type: 2, number: 0}

But now, what I am having to do is, repeat N amount of times the objects inside of the array. I’ve tried a few different functions to do this. Here’s one:

function replicate(arr, times) {
    var al = arr.length,
        rl = al*times,
        res = new Array(rl);
    for (var i=0; i<rl; i++)
        res[i] = arr[i % al];
    return res;
}

It works as expected:

let objarray_repeat = replicate(objarray, 2);

0 : {type: 2, number: 4768}
1 : {type: 2, number: 3168}
2 : {type: 2, number: 4768}
3 : {type: 2, number: 3168}

But when I try to do the exact same map function on the replicated array as shown above,

objarray_repeat.map((elem, i) =>  {
        if (i == 0) {
            elem.number = 1;
        }
        else {
            elem.number = 0;
        }
});

The output is incorrect:

0 : {type: 2, number: 0}
1 : {type: 2, number: 0}
2 : {type: 2, number: 0}
3 : {type: 2, number: 0}

As stated, I’ve tried numerous different functions to try to change up how I am replicating the objects in the array, but no matter what I try I cannot get the map function to work properly once I’ve replicated!

What’s the solution here for using map on a replicated array?

edit:

JSFiddle
https://jsfiddle.net/t2xpq1cz/

>Solution :

let objarray = [{
    type: 2,
    number: 4768
  },
  {
    type: 2,
    number: 3168
  }
];

let objarray_repeat = replicate(objarray, 2);


objarray_repeat = objarray_repeat.map((elem, i) => {
  return { ...elem,
    number: i === 0 ? 1 : 0
  }
});

console.log(objarray_repeat);



function replicate(arr, times) {
  let copyArr = [...arr];
  for (let i = 0; i < times; i++) {
    copyArr = [...copyArr, ...arr]
  }
  return copyArr;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading