0

I am looking for time-efficient ways to compare elements between arrays. I have two simplified short examples of the data my arrays could contain:

let a = ["mushrooms", "bread", "tomato", "sauce"]
let b = ["o", "e", "a"]

The lengths of the arrays I am working with exceed 500 000 elements. In my arrays I would be comparing every element from array b to every element in array a and computing a result depending on that. (i.e. checking how many Os the words from array a have and storing the result) However, I am currently using two loops - one iterating a and a nested one inside it iterating b.

My goal is to improve efficiency since I believe my algorithm is far from being time-efficient. I would love to learn about common practices which deal with this in a better way.

EDJ
  • 843
  • 3
  • 17
  • 37

2 Answers2

0

Another way to do this is using replace keywords with blank and compare the length

let a = ["mushrooms", "bread", "tomato", "sauce"];
let b = ["o", "e", "a"];
let c = [];

for(var i=0; i< b.length; i++)
{
    c.push(new RegExp(b[i],'g'));
}

for(var i=0; i < a.length; i++)
{
    for(var j=0; j < b.length; j++)
    {
        console.log(a[i], b[j], a[i].length - a[i].replace(c[j],'').length);
    }
}

EDIT: we did an loop efficiency test and for loop is the most efficient one.

Jules
  • 1,423
  • 13
  • 22
0

I am not sure to what level you are looking to compare and also how well it would work for 500,000 elements, but if you are looking for a simple A/B comparison, you could convert your arrays into strings and compare the strings.

function compareArrays(arr1, arr2) {
  const compare1 = JSON.stringify(arr1.sort());
  const compare2 = JSON.stringify(arr2.sort());
  return compare1 === compare2;
}
Ryan McCormick
  • 104
  • 1
  • 5