有這麼兩個數組數組
1 let metrodates = [ 2 "2008-01", 3 "2008-02", 4 "2008-03",..ect 5 ]; 6 let figures = [ 7 0, 8 0.555, 9 0.293,..ect 10 ]
想要這樣的結果oop
1 let result = [ 2 {data: 0, date: "2008-01"}, 3 {data: 0.555, date: "2008-02"}, 4 {data: 0.293, date: "2008-03"},..ect 5 ];
1 let result = []; 2 for(let index in metrodates){ 3 result.push({data: figures[index], date: metrodates[index]}); 4 }
此方案爲最原始方法,簡單,但過於lowspa
1 let result = metrodates.map((date,i) => ({date, data: figures[i]}));
此方案使用了ES6中的map,簡潔,但本質仍是遍歷,顯得有些lowcode
1 const zip = ([x,...xs], [y,...ys]) => { 2 if (x === undefined || y === undefined) 3 return []; 4 else
5 return [[x,y], ...zip(xs, ys)]; 6 } 7 let result = zip(metrodates, figures).map(([date, data]) => ({date, data}));
此方案使用了ES6+遞歸,顯得高大上起來了。對象
1 const isEmpty = xs => xs.length === 0; 2 const head = ([x,...xs]) => x; 3 const tail = ([x,...xs]) => xs; 4 const map = (f, ...xxs) => { 5 let loop = (acc, xxs) => { 6 if (xxs.some(isEmpty)) 7 return acc; 8 else
9 return loop([...acc, f(...xxs.map(head))], xxs.map(tail)); 10 }; 11 return loop([], xxs); 12 } 13 let result = map((date, data) => ({date, data}), metrodates, figures);
此方案是方案三的增強版,它能接受多個數組映射成對象數組,威力無比!blog