Home > database >  Comparing between 2 different nested arrays in JavaScript
Comparing between 2 different nested arrays in JavaScript

Time:06-05

I've been on this for a while but haven't been able to arrive at my desired result. I'd like to compare items in two arrays based on their indexes. Something like this:

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


I hope this is understood, enough. There is a very similar problem like this one. I don't know if it's right to post it here or open another ask a question, but they're both similar.

Thanks very much.

CodePudding user response:

You can try it :

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)

UPDATE : edit with suggest from @yes sir

CodePudding user response:

Xupitan used functional programming, which is the better approach in my opinion, but I tried to extend your code.

what you previously lacked was that you weren't keeping tracking of the first array, you were comparing every nested array, this approach is also valid but you need to then compare each results e.g., 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)

  • Related