1

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;
}, []);
0

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.