簡體   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