red17
red17

Reputation: 97

JavaScript - Check every element of 2D arrays for match

I am trying to compare an array of elements with the elements of a 2D array. If there is a match found, then the count for that row of 2D elements will increase. I managed to do it with the first row of 2D array however I do not know how to make the code keep checking for the next row of the 2D array.

var fruits=[
        ['apple', 'banana', 'mango'],
        ['grape', 'pineapple', 'blueberry'],
        ['strawberry', 'mangosteen']
];

var fruit_i_like=[
        ['grape', 'banana', 'pineapple']
];

//if found match from the first row of fruits, increment this var
var fruit1_count = 0;

//if found match from the second row of fruits, increment this var
var fruit2_count = 0;

//if found match from the third row of fruits, increment this var
var fruit3_count = 0;

for (var i = 0; i < fruit_i_like.length; i++) {
        for (var j = 0; j < fruits.length; j++){
            if (fruits[j].indexOf(fruit_i_like[i]) > -1) {
                fruit1_count++;
            }
            
        }
}

The expected result should be printing the number of match the fruit_i_like array has with every rows of the array fruits. For example, here fruit1_count would be 1, fruit2_count would be 2, fruit3_count would be 0.

Is there any way of checking the other rows, using pure JS? Thank you!

Upvotes: 1

Views: 1007

Answers (3)

Steve
Steve

Reputation: 918

I'm a little late to the party, but you can also do this with a pair of nested Array.reduce() methods, and using Array.includes() in the nested reduce to increment the count if included in the array.

const fruits = [
  ['apple', 'banana', 'mango'],
  ['grape', 'pineapple', 'blueberry'],
  ['strawberry', 'mangosteen']
];

const fruit_i_like = [
  ['grape', 'banana', 'pineapple']
];

const [fruit1_count, fruit2_count, fruit3_count] = fruits.reduce((a, c, i) => {
  a[i] = fruit_i_like[0].reduce((aa, cc) => aa + c.includes(cc), 0);
  return a;
}, new Array(fruits.length));

console.log({
  fruit1_count: fruit1_count,
  fruit2_count: fruit2_count,
  fruit3_count: fruit3_count
})

Upvotes: 0

DecPK
DecPK

Reputation: 25408

1) You can easily achieve the result using Set and simple for loop. You can first create an object of properties in which count you want as:

const obj = {
  fruit1_count: 0,
  fruit2_count: 0,
  fruit3_count: 0,
};

var fruits = [
  ["apple", "banana", "mango"],
  ["grape", "pineapple", "blueberry"],
  ["strawberry", "mangosteen"],
];

var fruit_i_like = [["grape", "banana", "pineapple"]];

const obj = {
  fruit1_count: 0,
  fruit2_count: 0,
  fruit3_count: 0,
};

const set = new Set(fruit_i_like[0]);

for (let i = 0; i < fruits.length; ++i) {
  const arr = fruits[i];
  for (let j = 0; j < arr.length; ++j) {
    if (set.has(arr[j])) obj[`fruit${i + 1}_count`]++;
  }
}

const { fruit1_count, fruit2_count, fruit3_count } = obj;
console.log(fruit1_count);
console.log(fruit2_count);
console.log(fruit3_count);

2) You can also use reduce and forEach here as:

var fruits = [
  ["apple", "banana", "mango"],
  ["grape", "pineapple", "blueberry"],
  ["strawberry", "mangosteen"],
];

var fruit_i_like = [["grape", "banana", "pineapple"]];

const obj = {
  fruit1_count: 0,
  fruit2_count: 0,
  fruit3_count: 0,
};

const set = new Set(fruit_i_like[0]);

const resultObj = fruits.reduce((acc, curr, i) => {
  curr.forEach((o) => {
    if (set.has(o)) acc[`fruit${i + 1}_count`]++;
  });
  return acc;
}, obj);

const { fruit1_count, fruit2_count, fruit3_count } = resultObj;
console.log(fruit1_count);
console.log(fruit2_count);
console.log(fruit3_count);

Upvotes: 1

Jack Bashford
Jack Bashford

Reputation: 44105

Probably better to use an array than variables in this case, so you don't have to hardcode names and definitions. In this case, you'll get an ordered list of each fruit's count at the end from the array, in the order you initially put them in the fruits array (not sure why fruit_i_like is two-dimensional, either).

var fruits = [
  ['apple', 'banana', 'mango'],
  ['grape', 'pineapple', 'blueberry'],
  ['strawberry', 'mangosteen']
];

var fruit_i_like = [
  ['grape', 'banana', 'pineapple']
];

let fruitCounts = [];

fruits.forEach((fruitsList, i) => {
  fruitCounts.push(0);
  fruit_i_like[0].forEach(likedFruit => {
    if (fruitsList.includes(likedFruit)) {
      fruitCounts[i]++;
    }
  });
});

fruitCounts.forEach((count, i) => {
  console.log(`Fruit count ${i} = ${count}`);
});

Upvotes: 2

Related Questions