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?

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


  • 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.


function modifyArray(arrays) {
    return arrays.map(array => {
        return { coordinates: array.slice(0, 2), reach: array[2], power: 0 };
  • \$\begingroup\$ is it ok to have a function with two return statements such as this, in terms of an efficient piece of code? \$\endgroup\$ – Chasmatu Oct 4 '18 at 5:26
  • 1
    \$\begingroup\$ @Saqib two returns has no impact on performance, at all. \$\endgroup\$ – FreezePhoenix Oct 4 '18 at 12:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.