# Converting an array into an object

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?

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];
}


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));

• 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. – SuperBiasedMan Oct 13 '15 at 11:48
• @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. – Joseph Oct 13 '15 at 12:03
• 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. – SuperBiasedMan Oct 13 '15 at 12:06

My suggestion is:

var arr = ['akira', 9248, 'padilla', 100];
var obj = {};
var len = arr.length;
for (; len;) {
obj[arr[--len]] = arr[--len];
}