# Modify array of arrays to create custom array of objects

I have an array of arrays and I want to create an array of objects from it. There are custom properties to which I want to associate the sub-array values. I have the following array:

var testArray = [[1,5,10], [10,20,7], [11,10,25]];


I am modifying it to create the following

[{
coordinates: [1, 5],
reach: 10,
power: 0
},
{
coordinates: [10, 20],
reach: 7,
power: 0
},
{
coordinates: [11, 10],
reach: 25,
power: 0
}]


For this I have written the following code.

function modifyArray(array) {
return array.map(array => {
return Object.assign({}, { coordinates: array.slice(0, 2), reach: array[2], power: 0 });
});
}


I get the desired result. My question is if this is a good way to modify this type of data performance wise, since the function has two return statements. How can I improve on this code?

• But can the original array be modified or not ? Do you have to preserve the original ? – Isac Oct 3 '18 at 11:55
• I would like to preserve the original. However other way around could also be possible but not recommended. – Chasmatu Oct 3 '18 at 12:17
• But is your sole purpose to improve on speed ? – Isac Oct 3 '18 at 12:57
• It was part of my coding challenge and I want to improve my solution to be acceptable as an "efficient" solution. – Chasmatu Oct 3 '18 at 13:19
• To make it efficient without mutating the original array you can remove both assign and slice. Here is a jsperf i made on that – Isac Oct 3 '18 at 13:30

# Overview

• You're overwriting the name array in defining the mapping param.
• You don't need to assign to a new object. This is done for you.

# Rewrite

function modifyArray(arrays) {
return arrays.map(array => {
return { coordinates: array.slice(0, 2), reach: array[2], power: 0 };
});
}

• is it ok to have a function with two return statements such as this, in terms of an efficient piece of code? – Chasmatu Oct 4 '18 at 5:26
• @Saqib two returns has no impact on performance, at all. – FreezePhoenix Oct 4 '18 at 12:24