Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

211
Views
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!

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!