假设我们有一个像这样的数组的数组-
const arr = [ ["Ashley","2017-01-10",80], ["Ashley","2017-02-10",75], ["Ashley","2017-03-10",85], ["Clara","2017-01-10",90], ["Clara","2017-02-10",82] ];
我们需要编写一个JavaScript函数,该函数接受一个这样的数组作为第一个也是唯一的输入。
然后,该函数应基于输入数组构造一个新的对象数组。该数组应为输入数组的每个唯一子数组包含一个对象。(在此上下文中,唯一是指具有第一个元素唯一性的子数组)。
每个对象必须具有以下架构-
const output = [ {"name":"Ashley", "2017-01-10":80, "2017-02-10":75, "2017-03-10":85}, {"name":"Clara", "2017-01-10":90, "2017-02-10":82} ];
const arr = [ ["Ashley","2017-01-10",80], ["Ashley","2017-02-10",75], ["Ashley","2017-03-10",85], ["Clara","2017-01-10",90], ["Clara","2017-02-10",82] ]; const groupArray = (arr = []) => { let grouped = []; grouped = arr.reduce(function (hash) { return function (r, a) { if (!hash[a[0]]) { hash[a[0]] = { name: a[0] }; r.push(hash[a[0]]); } hash[a[0]][a[1]] = a[2]; return r; }; } (Object.create(null)), []); return grouped; } console.log(groupArray(arr));
输出结果
控制台中的输出将是-
[ { name: 'Ashley', '2017-01-10': 80, '2017-02-10': 75, '2017-03-10': 85 }, { name: 'Clara', '2017-01-10': 90, '2017-02-10': 82 } ]