在 JavaScript 中比较 2 个不同的嵌套数组

Comparing between 2 different nested arrays in JavaScript

我已经研究了一段时间,但未能达到我想要的结果。 我想根据索引比较两个数组中的项目。像这样:

const first = 0;
const second = 1;
const result = []; // should equal (false, true, false)

const final = [[[2,3],[1,1]],[[4,2],[3,0]],[[0,3],[1,1]]];

for (let i = 0; i < final.length; i++) {
    for (let j = 0; j < final[i].length; j++){
//Comparison between ((2 and 3) && (1 and 1)) with a single result.
//Should also compare between ((4 and 2) && (3 and 0)) and many other nested arrays
//This logic is not the right one as it can't do the comparison as intended.
      if (final[i][j][first] > final[i][j][second]) {
result.push(true);
    } else result.push(false);
  }


我希望这已经足够理解了。有一个与此非常相似的问题。我不知道在这里 post 还是另开一个问题是正确的,但它们都很相似。

非常感谢。

你可以试试:

const first = 0;
const second = 1;

const final = [[[2,3],[1,1]],[[4,2],[3,0]],[[0,3],[1,1]]];

const result = final.map(([e1, e2]) => (e1[first] > e1[second] && e2[first] > e2[second]))
console.log(result)

更新:根据@yes sir

的建议进行编辑

Xupitan 使用函数式编程,我认为这是更好的方法,但我尝试扩展您的代码。

您之前缺少的是您没有跟踪第一个数组,而是比较每个嵌套数组,这种方法也有效,但您需要然后比较每个结果,例如 result[i] && result [i+1].

const first = 0;
const second = 1;
const result = []; // should equal (true, true, false)

const final = [[[2,3],[1,1]],[[4,2],[3,0]],[[0,3],[1,1]]];

let k=0

for (let i = 0; i < final.length; i++) {
    for (let j = 0; j < final[i].length; j++){
        //Comparison between ((2 and 3) && (1 and 1)) with a single result.
        //Should also compare between ((4 and 2) && (3 and 0)) and many other nested arrays
        //This logic is not the right one as it can't do the comparison as intended.
        if (final[i][j][first] > final[i][j][second]) {
            if(k > 0){
                result[i] = true
            }
            result[i] = true
        }else{
            //first false exit
            result[i] = false;
            break;
        } 
        k++
  }
  k=0
}

console.log(result)