1
\$\begingroup\$

I have an array of this fashion:

var arr = ["akira",9248,"padilla",100];

I'm using filter to take the names and the points:

var names = arr.filter(function(e,i){return i%2 == 0});
var points = arr.filter(function(e,i){return i%2 !== 0});

Then I do this to obtain turn it into object:

console.log(JSON.stringify(_.object(names,points)));

What's best in terms of performance/JS quality?

\$\endgroup\$
4
\$\begingroup\$

Could you do it this way which would mean you're only traversing the array once?

var obj = {};

for (var i=0; i < arr.length - 1; i = i + 2) {
    obj[arr[i]] = arr[i+1];
}         
\$\endgroup\$
1
\$\begingroup\$

I was wondering if I could do the same with reduce... and I did:

var arr = ["akira",9248,"padilla",100];

var obj = arr.reduce((carry, item, i, array) => {
  if(!(i%2)) carry[item] = array[i+1];
  return carry;
}, {});

document.write(JSON.stringify(obj));

\$\endgroup\$
  • \$\begingroup\$ You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and how it improves upon the original) so that the author can learn from your thought process. \$\endgroup\$ – SuperBiasedMan Oct 13 '15 at 11:48
  • \$\begingroup\$ @SuperBiasedMan *"Make sure your answer provides that – or a viable alternative. The answer can be “don’t do that”, but it should also include “try this instead”" codereview.stackexchange.com/help/how-to-answer. Besides, the other guy pretty much already answered a more optimized version, and reduce is pretty much self-explanatory if you read what it does. \$\endgroup\$ – Joseph Oct 13 '15 at 12:03
  • \$\begingroup\$ But you haven't explained why reduce is better or what's bad about the original code. That's what I think you should add. reduce may not be self explanatory to the OP, that might be why they didn't use it. \$\endgroup\$ – SuperBiasedMan Oct 13 '15 at 12:06
1
\$\begingroup\$

My suggestion is:

var arr = ['akira', 9248, 'padilla', 100];
var obj = {};
var len = arr.length;
for (; len;) {
  obj[arr[--len]] = arr[--len];
}
alert(JSON.stringify(obj));
\$\endgroup\$
  • 1
    \$\begingroup\$ Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and how it improves upon the original) so that the author can learn from your thought process. \$\endgroup\$ – SuperBiasedMan Oct 13 '15 at 11:39
  • 1
    \$\begingroup\$ The question is "What's best in terms of performance/JS quality?" and my answer is exactly about performance. \$\endgroup\$ – Valentin Oct 13 '15 at 11:58

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.