我有大数据结构要操作,我在将类似数据排序到子数组时遇到了一些问题。
var arr = [2016-12-16, 2016-12-16, 2016-12-17, 2016-12-17, 2016-12-17, 2016-12-17, 2016-12-18, 2016-12-18, 2016-12-19];
我想要这样排序。
[[2016-12-16, 2016-12-16], [ 2016-12-17, 2016-12-17, 2016-12-17, 2016-12-17],[2016-12-18, 2016-12-18] [2016-12-19]]
答案 0 :(得分:0)
Array#reduce
使用对象作为哈希值将数组放入数组数组中:
var arr = ['2016-12-16', '2016-12-16', '2016-12-17', '2016-12-17', '2016-12-17', '2016-12-17', '2016-12-18', '2016-12-18', '2016-12-19'];
var result = arr.reduce(function(r, item) {
(r.hash[item] || (r.hash[item] = r.arr[r.arr.push([]) - 1])).push(item);
return r;
}, { arr: [], hash: {} }).arr;
console.log(result);

答案 1 :(得分:0)
最简单的方法是使用字典(JS对象自然会起作用)。
var datesArray = [ "2016-12-16", "2016-12-16", "2016-12-17", "2016-12-17", "2016-12-17", "2016-12-17", "2016-12-18", "2016-12-18", "2016-12-19" ]; //I've corrected the syntax for this to make each date a string, rather than a sequence of subtractions
var datesCount = {};
datesArray.forEach(function(date){
if(!datesCount[date])
datesCount[date] = []
datesCount[date].push(date);
});
此时,您有一组组数组,每个数组都包含特定日期的每个实例。您可以使用Object.getOwnPropertyNames
对其进行迭代,并将每个数组放入更大的数组中,或者直接使用它。
答案 2 :(得分:0)
尝试将代码划分为子问题-
这是我为其他目的而编写的代码,出于说明目的对其进行了修改。 可能还有更有效的编写方法,我仍在学习。
const dateStringSort = (array) => {
//assign to a new array - wont change exist array
const arr = [].concat(array);
//sort elements
arr.sort();
//identify repeated elements and group them to sub arrays.
const arr1 = []; //assign another array to prevent inifinty loops
while (arr.length>0){
let i = arr[0];
let filtered = arr.filter(item=>item===i);//return new array with all reapeted elements
arr1.push(filtered); //push the filtered array to new array as a sub array
arr.splice(0,(filtered.length)); //delete all the repeated elements from arr to prevent double sub araays
};
//return new array
return arr1;
};
//run function
const originArray = ["2016-12-16", "2016-12-16", "2016-12-17", "2016-12-17", "2016-12-17", "2016-12-17", "2016-12-18", "2016-12-18", "2016-12-19"];
const newArray = dateStringSort(originArray);