繁体   English   中英

比较 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);
  }


我希望这被理解,足够了。 有一个非常相似的问题。 我不知道在这里发布或打开另一个问题是否正确,但它们都很相似。

非常感谢。

你可以试试 :

 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) // with non arrow function function compareArr(arr, first, second) { return arr.map(function (ele) { return ele[0][first] > ele[0][second] && ele[1][first] > ele[1][second] }) } console.log(compareArr(final, first, second)) // with non map function : function compareArr1(arr, first, second) { let result1 = [] for(let i = 0; i < arr.length; i++) { result1[i] = true for(let j = 0; j < arr[i].length; j++) { if(!(arr[i][j][first] > arr[i][j][second])) result1[i] = false } } return result1 } console.log(compareArr1(final, first, second))

更新:编辑@是先生的建议

更新:关于([e1,e2])

正常: Array.map((ele) => .....)结构为 ele 是[a, b]

它可以使用相同的: Array.map(([a, b]) => .....)

它的文档: 解构分配

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM