假设我有一个看起来像这样的样本数组。
在这里的代码输出中它看起来像
[[2131, 2016-01-01, 1:00 PM, FA1], [2131, 2016-01-01, 2:00 PM, FA1], [2131, 2016-01-01, 3:00 PM, FA1], [2132, 2016-01-02, 4:00 PM, FA1].....]
我怎样才能看起来像这样?
我的意思是始终按日期对数据进行分组,并且只获取每个组的最后一组和第一组数据
我希望你得到我的观点TYSM
答案 0 :(得分:3)
确定。根据您给出的输入,我构造了数组并根据需要获得输出。希望它有所帮助。
var inputarr = [ [ 2131, "2016-01-01", "1:00 PM", "FA1" ],
[ 2131, "2016-01-01", "2:00 PM", "FA1" ],
[ 2131, "2016-01-01", "3:00 PM", "FA1" ],
[ 2132, "2016-01-02", "4:00 PM", "FA1" ],
[ 2132, "2016-01-02", "5:00 PM", "FA1" ],
[ 2132, "2016-01-02", "6:00 PM", "FA1" ],
[ 2133, "2016-01-03", "7:00 PM", "FA1" ],
[ 2133, "2016-01-03", "8:00 PM", "FA1" ],
[ 2133, "2016-01-03", "9:00 PM", "FA1" ] ];
map = {};
for ( var element in inputarr) {
if (!map[inputarr[element][1]]) {
map[inputarr[element][1]] = [];
}
map[inputarr[element][1]].push(inputarr[element]);
}
output = [];
for ( var key in map) {
output.push(map[key].shift());
output.push(map[key].pop());
}
console.log(output);
输出:
[ [ 2131, '2016-01-01', '1:00 PM', 'FA1' ],
[ 2131, '2016-01-01', '3:00 PM', 'FA1' ],
[ 2132, '2016-01-02', '4:00 PM', 'FA1' ],
[ 2132, '2016-01-02', '6:00 PM', 'FA1' ],
[ 2133, '2016-01-03', '7:00 PM', 'FA1' ],
[ 2133, '2016-01-03', '9:00 PM', 'FA1' ] ]
答案 1 :(得分:2)
你可以做这样的事情
let arr = [[2131, "2016-01-01", "1:00 PM", "FA1"], [2131, "2016-01-01", "2:00 PM", "FA1"], [2131, "2016-01-01", "3:00 PM", "FA1"]
, [2132, "2016-01-02", "4:00 PM", "FA1"], [2132, "2016-01-02", "5:00 PM", "FA1"], [2132, "2016-01-02", "6:00 PM", "FA1"]
, [2133, "2016-01-03", "7:00 PM", "FA1"], [2133, "2016-01-03", "8:00 PM", "FA1"], [2133, "2016-01-03", "9:00 PM", "FA1"]]
let startMap = {};
let endMap = {};
let dateArray = [];
let resultArray = [];
for(let element of arr){
console.log(element);
if(startMap[element[1]] === undefined){
startMap[element[1]] = element;
dateArray.push(element[1]);
}
endMap[element[1]] = element;
}
for(let date of dateArray){
resultArray.push(startMap[date]);
resultArray.push(endMap[date]);
}
console.log(resultArray);
答案 2 :(得分:2)
您可以使用此ES6脚本:
const data = [
[2131, "2016-01-01", "1:00 PM", "FA1"],
[2131, "2016-01-01", "2:00 PM", "FA1"],
[2131, "2016-01-01", "3:00 PM", "FA1"],
[2132, "2016-01-02", "4:00 PM", "FA1"],
[2132, "2016-01-02", "5:00 PM", "FA1"],
[2132, "2016-01-02", "6:00 PM", "FA1"],
[2133, "2016-01-03", "7:00 PM", "FA1"],
[2133, "2016-01-03", "8:00 PM", "FA1"],
[2133, "2016-01-03", "9:00 PM", "FA1"]
];
const result = [].concat(...data.reduce( (acc, a) =>
acc.set(a[1], (acc.get(a[1]) || []).slice(0, 1).concat([a]))
, new Map).values());
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
reduce
与空Map
一起用作起始值。然后使用日期作为键填充Map
,并将匹配的原始值作为每个键的数组值。使用slice
时,只有在添加新条目时才会保留此类数组的第一个条目。这样,每个数组中最多只能有2个值。
reduce
返回最终Map
后,会使用values
从中提取值,并将其作为参数传播到concat
,这将使其再次成为一个平面数组