Charles L.
Charles L.

Reputation: 1970

JavaScript compare an array to an object of arrays to see if their values match

I have an array that I'm trying to compare to see if the values in array 1 are in any of the arrays inside an object:

arr1 = [9]

obj1 = {Cards: [8,5], Loans: [], Shares: [0,9,25]}

I'm using JavaScript(ECMAScript 5) to try and do this, all I need is true to be returned if any of the values in arr1 are found inside obj1.

What I've tried:

function arraysEqual(_arr1, _arr2) {
  if (!Array.isArray(_arr1) || !Array.isArray(_arr2) || _arr1.length !== _arr2.length)
    return false;
  var arr1 = _arr1.concat().sort();
  var arr2 = _arr2.concat().sort();
  for (var i = 0; i < arr1.length; i++) {
    if (arr1[i] !== arr2[i])
      return false;
  }
  return true;
}

This however will just test to see if the arrays in specific so I have to call this three times to check the values, even this however will return false when I try:

arraysEqual(arr1, obj1.Shares)

Would like this to be done with one call

Upvotes: 1

Views: 71

Answers (4)

Paul Bota
Paul Bota

Reputation: 141

This one should work:

let arr1 = [9, 8]

let obj1 = {Cards: [8,5], Loans: [], Shares: [0,9,25]}

function check(arr1, obj1) {
  let values = Object.keys(obj1).map((key)=> obj1[key]).reduce((acc, val) => acc.concat(val));

   for(let n of arr1) {
        if(values.indexOf(n) === -1) return false;
      }
   return true;
}
  
console.log(check(arr1, obj1));

Upvotes: 0

adiga
adiga

Reputation: 35232

You could check if every item in arr1 is in arr2 using indexOf:

function compare(arr1, arr2) {
  return arr1.every(function(n){
    return arr2.indexOf(n) > -1
  })
}

var arr = [9],
    obj = { Cards: [8,5], Loans: [], Shares: [0,9,25] }

console.log(compare(arr, obj.Shares))
console.log(compare(arr, obj.Cards))

Upvotes: 2

Prince Devadoss
Prince Devadoss

Reputation: 416

Another way of doing is using Array.prototype.some(),

var array = [8,9];
var obj = {o1:[18,99], o2:[19], o3:[8,56]};
var p = array.some((arr) => {
    var ret =  Object.values(obj).find((value) => {
        return value.find((val) => val === arr);
    });
    return ret ? true : false;

});

console.log(p);

Upvotes: 0

izeke
izeke

Reputation: 75

You can use a for...in loop to iterate through the object, then you can use a for loop to iterate through the main array, finally using an array.includes on your secondary array (from the object) to see if any elements from the main array exist in the secondary array

arr1 = [3]
obj1 = {Cards: [8,5], Loans: [], Shares: [0,9,25]};

for (arr2 in obj1)
{
  for (i = 0; i < arr1.length; i++) {
    if (obj1[arr2].includes(arr1[i]))
    {
      console.log('exists');
    }
  }
}

Upvotes: 0

Related Questions