[英]Group JavaScript array items by comparing items
I have an array like this:我有一个这样的数组:
var oArr = [
{ id: "d1", x: 2, y: 2 },
{ id: "d1", x: 3, y: 3 },
{ id: "d1", x: 5, y: 3 },
{ id: "d1", x: 5, y: 7 },
{ id: "d1", x: 3, y: 6 },
];
I want to subtract all the y
properties to each other and test if it is smaller then the given threshold value.我想将所有y
属性相减并测试它是否小于给定的阈值。
And finally group items in nested-arrays...最后将嵌套数组中的项目分组...
var threshold =2;
So my expected output is:所以我的预期输出是:
var result= [
[ { id: "d1", x: 2, y: 2 },{ id: "d1", x: 3, y: 3 }, { id: "d1", x: 5, y: 3 }],
[ { id: "d1", x: 5, y: 7 }, { id: "d1", x: 3, y: 6 }]
];
Any suggestions or advice would be appreciated.任何建议或意见将不胜感激。
You could reduce the array and check if the delta is not greater then the given threshold
.您可以减少数组并检查增量是否不大于给定的threshold
。
This solution requires a sorted array.此解决方案需要一个排序数组。
var array = [{ id: "d1", x: 2, y: 2 }, { id: "d1", x: 3, y: 3 }, { id: "d1", x: 5, y: 3 }, { id: "d1", x: 5, y: 7 }, { id: "d1", x: 3, y: 6 }], threshold = 2, result = array .sort(({ y: a }, { y: b }) => a - b) .reduce((r, o, i, a) => { if (!i || oy - a[i - 1].y > threshold) { r.push([]); } r[r.length - 1].push(o); return r; }, []); console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.