work-react
work-react

Reputation: 33

How to get number occurrences of any element of an array in another array in Javascript?

I have an array:

const myArray1 = [{tags: ['tag-1', 'tag-2']}, {tags: ['tag-1']}, {tags: ['tag-5', 'tag-8']}]

And an array2:

const myArray2 = [
  {
    tags: [
       "tag-122",
      "tag-1",
      "tag-2",
      "tag-12"
    ]
  },
  {
    tags: [
      "tag-1",
      "tag-10",
      "tag-12"
    ]
  },
  {
    tags: [
      "tag-5"
    ]
  }
];

I want to get an array

const resultArray = [{tags: ['tag-1', 'tag-2'], count: 2}, {tags: ['tag-1'], count: 2}, {tags: ['tag-5', 'tag-8'], count: 1}]

For every element in myArray1 check if any element of array tags in myArray1 contains in myArray2. if contains, find the count of occurrences

I try to make an array of myArray2 tags and then find occurrences in array for every element of myArray1

const result = myArray2.reduce((acc, el) => {
  el.tags && el.tags.map(tag => acc.push(tag));
  return acc;
}, []);

Upvotes: 1

Views: 86

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370789

I'd transform the myArray2 into an array of Sets for reduced computational complexity, then .map the array2 and check if .some of the tags being iterated over exists in the set, counting the number of occurrences with reduce:

const myArray1=[{tags:["tag-1","tag-2"]},{tags:["tag-1"]},{tags:["tag-5","tag-8"]}],
      myArray2=[{tags:["tag-122","tag-1","tag-2","tag-12"]},{tags:["tag-1","tag-10","tag-12"]},{tags:["tag-5"]}];

const arr2Sets = myArray2.map(({ tags }) => new Set(tags));

const resultArray = myArray1.map(({ tags }) => {
  const count = arr2Sets.reduce(
    (a, set) => a + tags.some(tag => set.has(tag)),
    0
  );
  return { tags, count };
});
console.log(resultArray);

Upvotes: 2

Related Questions