我有一个数组:
var items = [[1,1,2,2,3,3,4,4,5,5],[0,0,0,1,0,1,0,1,0,1]];
换句话说,我想循环遍历 items[0] 和 items[1] 的元素并收集所有元素,直到找到 items[0] 的三个唯一值。
我想要的输出是:
output = [[1,1,2,2,3,3],[0,0,0,1,0,1]];
最佳答案
如果我理解正确,那么以下内容将满足您的要求。
function threeDistincts(items) {
var distincts = 0, inArr = false;
for (var i = 0; i < items[0].length; i++) {
inArr = false;
for (var j = 0; j < i; j++) {
if (items[0][j] === items[0][i]) {
inArr = true;
break;
}
}
if (!inArr) distincts++;
if (distincts === 4) break;
}
items[0].length = items[1].length = i;
}
这样调用它:
var items = [[1,1,2,2,3,3,3,4,5,5],[0,0,0,1,0,1,0,1,0,1]];
threeDistincts(items);
// items = [[1,1,2,2,3,3],[0,0,0,1,0,1]];
此函数的另一个版本,使用 indexOf
(如 DTing 建议),将内部循环(在原始函数中)仅限于不同元素,但考虑到高 complexity of Array.indexOf
和 Array.push 实现,不能保证更好的性能。
function threeDistincts(items) {
var arr = [];
for (var i = 0; i < items[0].length; i++) {
if (arr.indexOf(items[0][i]) === -1) arr.push(items[0][i]);
if (arr.length === 4) break;
}
items[0].length = items[1].length = i;
}
关于javascript - 按其中一个数组的前 3 个唯一值对数组进行切片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31014786/