我需要你对这个数组的帮助,我真的不知道如何排序:
[{userId: "3t5bsFB4PJmA3oTnm", from: 1, to: 6},
{userId: "3t5bsFB4PJmA3oTnm", from: 7, to: 15},
{userId: "3t5bsFB4PJmA3oTnm", from: 172, to: 181},
{userId: "3t5bsFB4PJmA3oTnm", from: 182, to: 190}]
进入那个:
[{userId: "3t5bsFB4PJmA3oTnm", from: 1, to: 15},
{userId: "3t5bsFB4PJmA3oTnm", from: 172, to: 190}]
你可以帮帮我吗?它可以是lodash或下划线,我试过两个,真的无法解决这个问题
答案 0 :(得分:0)
您可以检查userId
,如果相同,检查项目是否有序,然后更改to
属性。
适用于已排序的项目。如果没有排序,你可以在之前进行排序。
data.sort(function (a, b) {
return a.userId.localeCompare(b.userId) || a.from - b.from;
});
var data = [{ userId: "3t5bsFB4PJmA3oTnm", from: 1, to: 6}, { userId: "3t5bsFB4PJmA3oTnm", from: 7, to: 15 }, { userId: "3t5bsFB4PJmA3oTnm", from: 172, to: 181 }, { userId: "3t5bsFB4PJmA3oTnm", from: 182, to: 190 }],
result = data.reduce(function (r, a) {
var last = r[r.length - 1] || {};
if (last.userId === a.userId && last.to + 1 === a.from) {
last.to = a.to;
} else {
r.push({ userId: a.userId, from: a.from, to: a.to });
}
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }