Underline Solution:
output = _.object(..._.partition(input, (_, i) => !(i % 2)))
_.partition will split the array into [['name', 'age'], ["tom", "20"]] . In other words, it returns an array containing two subarrays - in this case, one array of keys and one array of values. _.object takes an array of keys and an array of values as parameters, so we use ... to pass subarrays to the value returned by _.partition , into it as two parameters.
If you use a very functional semantic code:
const even = i => !(i % 2); const index = fn => (_, i) => fn(i); output = _.object(..._.partition(input, index(even)))
Recursive solution:
function arrayToObject([prop, value, ...rest], result = {}) { return prop ? arrayToObject(rest, Object.assign(result, {[prop]: value})) : result; }
Iterative solution:
function arrayToObject(arr) { const result = {}; while (arr.length) result[arr.shift()] = arr.shift(); return result; }
user663031
source share