3
\$\begingroup\$

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?

\$\endgroup\$
7
  • \$\begingroup\$ But can the original array be modified or not ? Do you have to preserve the original ? \$\endgroup\$
    – Isac
    Commented Oct 3, 2018 at 11:55
  • \$\begingroup\$ I would like to preserve the original. However other way around could also be possible but not recommended. \$\endgroup\$
    – Saqib S
    Commented Oct 3, 2018 at 12:17
  • \$\begingroup\$ But is your sole purpose to improve on speed ? \$\endgroup\$
    – Isac
    Commented Oct 3, 2018 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\$
    – Saqib S
    Commented Oct 3, 2018 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
    Commented Oct 3, 2018 at 13:30

1 Answer 1

2
\$\begingroup\$

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 };
    });
}
\$\endgroup\$
2
  • \$\begingroup\$ is it ok to have a function with two return statements such as this, in terms of an efficient piece of code? \$\endgroup\$
    – Saqib S
    Commented Oct 4, 2018 at 5:26
  • 1
    \$\begingroup\$ @Saqib two returns has no impact on performance, at all. \$\endgroup\$ Commented Oct 4, 2018 at 12:24

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.