javascript - 按其中一个数组的前 3 个唯一值对数组进行切片

标签 javascript arrays

我有一个数组:

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]];

Working Fiddle .

此函数的另一个版本,使用 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/

相关文章:

javascript - Google 托管库 - 版本流行度与最新版本

arrays - 如何使用graph api在azure b2c中创建多个用户?

javascript - jQuery 选择器仅在父级没有 attr 时

javascript - three.js中 `THREE.OrbitControls`的相机位置变化

javascript - 如何仅在 ES2015 中生成从 0 到 n 的数字范围?

C编程动态初始化二维数组

arrays - 数组复制在 Swift 中显示 0 1 而不是 true false

javascript - 用新值更新现有的 JS 关联数组

javascript - 在 Javascript 中使用特殊键进行按键操作

javascript - 通过VBA提取隐藏在页面源代码中的javascript表