如何编写一个脚本,将数组的元素分组为数组(或数组对象),其中最后一个是按序列分组的元素数组。
如果下一个元素Id是序列的一部分,则它属于prev组,否则将创建新的数组,元素将落入其中。
如果元素Id大于1-是相同的序列=当前数组。
如果元素Id大于2-是下一个序列= next (新)数组.
如果来自所有各方的元素邻居Id都大于当前Id,则当前元素将创建一个包含自身的数组,并且它的键将是它自己的Id.。
,它无论结果是数组还是对象生成键都很容易,但是组元素现在对我来说很难。
您可以尝试用JavaScript编写,甚至可以使用Lodash库.
const data = [
{id: 1},
{id: 2},
{id: 3},
{id: 7},
{id: 9},
{id: 10},
{id: 12},
{id: 14},
{id: 15},
{id: 16}];==========================================
const result = [
0/"1-4": [
{id: 1},
{id: 2},
{id: 3},
{id: 4}],
1/"7": [
{id: 7}],
2/"9-10": [
{id: 9},
{id: 10}],
3/"12": [
{id: 12}],
4/"14-16": [
{id: 14},
{id: 15},
{id: 16}]];发布于 2018-04-27 15:51:57
您可以使用reduce来创建一个数组,其中下一个期望的数字是当前项id加上一个。
const data = [
{id: 1},
{id: 2},
{id: 3},
{id: 7},
{id: 9},
{id: 10},
{id: 12},
{id: 14},
{id: 15},
{id: 16}]
.sort((a,b)=>a.id-b.id)//make sure it is sorted by id
.reduce(
([result,nextNum],item)=>{//nextNum is the next expected number
if(nextNum===undefined){//first time nextNum is undefined
nextNum=item.id;//set nextNum to id of current item
result.push([]);//add empty array
}
if(!(nextNum===item.id)){//current item id is not the expected next number
result.push([]);//add empty array
}
result[result.length-1].push(item);//add item to last array of the array of arrays
return [result,item.id+1];//next expected number is current item id + 1
},
[[],undefined]//initial values for result and nextNum
);
console.log(data)
发布于 2018-04-27 19:19:24
您可以使用链接的Array.reduce()调用来创建所需的结构:
const data = [{"id":1},{"id":2},{"id":3},{"id":7},{"id":9},{"id":10},{"id":12},{"id":14},{"id":15},{"id":16}];
const arrayOfGroups = data
.reduce((r, o, i) => {
// if first or not sequence add new sub array
if(!r.length || o.id !== data[i - 1].id + 1) r.push([]);
// push to last sub array
r[r.length - 1].push(o);
return r;
}, []);
const objectOfGroups = arrayOfGroups.reduce((r, a, i) => {
const start = a[0].id;
const end = a[a.length - 1].id;
// if start and end are equal, add just start (to main the order of insertion, start can be just a number)
const key = start === end ?
`${i}/${start}` : `${i}/${start}-${end}`;
r[key] = a;
return r;
}, {});
console.log('arrayOfGroups', arrayOfGroups);
console.log('objectOfGroups', objectOfGroups);
发布于 2018-04-27 19:27:08
您可以通过检查结果集的最后一个数组并检查最后一个对象的id (如果它在需要的范围内)来使用单一循环方法。
如果没有,则向结果集中添加一个新的空数组。稍后将实际对象推到最后一个数组。
var data = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 7 }, { id: 9 }, { id: 10 }, { id: 12 }, { id: 14 }, { id: 15 }, { id: 16 }],
grouped = data.reduce((r, o) => {
var last = r[r.length - 1];
if (!last || last[last.length - 1].id + 1 !== o.id) {
r.push(last = []);
}
last.push(o);
return r;
}, []);
console.log(grouped);.as-console-wrapper { max-height: 100% !important; top: 0; }
https://stackoverflow.com/questions/50065746
复制相似问题