2

Goal: TO SEE IF I CAN MATCH TWO ARRAYS AND RETURN BOOLEAN true OR false

Problem: I want to ask if there is a better solution to matching two arrays for same values, for eg.

"arr1": ["hello, world, droids"],
"arr2": ["hello, there, Kenobi"]

One way I found was from another SO answer here. But this approach seems too far-fetched when we have utility libraries like underscore and lodash.

What I am thinking is something like:

const __ = require('underscore')

if(__.difference(arr1, arr2).length > 0) {
 console.log('not same')
} else {
 console.log('same')
}

I am extremely new to programming so I am not sure which one of them should be viable for production or if what I am thinking is even right in first place.

I will also add the SO answer next which I found.

var areJSONArraysEqual = function(jsonArray1,
                                    jsonArray2) {

                                if(jsonArray1.length===0||jsonArray2.length===0){
                                    if(jsonArray1.length===0 && jsonArray2.length===0){
                                        return true;
                                    }else{
                                        return false;
                                    }
                                }

                                for(var i=0;i<jsonArray1.length;i++){
                                    for ( var key in jsonArray1[i]) {
                                        if(jsonArray1[i][key].length>1){
                                            return areJSONArraysEqual(jsonArray1[i][key],jsonArray2[i][key])
                                        }
                                        if (jsonArray1[i][key] != jsonArray2[i][key]) {
                                            return false;
                                        }
                                    }
                                }
                                return true;
                            };

1 Answers1

2

It appears that what you are trying to do is a deep equality comparison. You can do this in Underscore (and Lodash) with _.isEqual. For example:

const _ = require('underscore');

const arr1 = ["hello, world, droids"];
const arr2 = ["hello, there, Kenobi"];

console.log(_.isEqual(arr1, arr2)); // false
Julian
  • 4,176
  • 19
  • 40