-2

I have 2 variables say a=1,2,3,4 and b=1,2 , I want to compare these 2 variables and form a new variable with common values, please help me

Elza
  • 15
  • 3
  • `a=1,2,3,4` is just the same as `a=4`. See [What does a comma do in JavaScript expressions?](https://stackoverflow.com/q/3561043) and [Comma operator returns first value instead of second in argument list?](https://stackoverflow.com/q/5580596) – VLAZ May 06 '21 at 15:37
  • 2
    [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users), [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) – Andreas May 06 '21 at 15:37

2 Answers2

0

Assuming you meant:

a="1,2,3,4"
b="1,2"

You could break those comma delimited values into arrays and then get the intersections of the arrays. Here's an example:

const ArrayA = a.split(",");
const ArrayB = b.split(",");

const intersection = ArrayA.filter(value => ArrayB.includes(value));
const commonCSV = intersection.join(",");
Erik
  • 20,526
  • 8
  • 45
  • 76
0

var a = [1, 2, 3, 4];
var b = [1, 2];

// Take unqiue values from a and concat with unique values from b
const occurrenceMap = [...new Set(a)].concat([...new Set(b)]).reduce((map, el) => {
  map.set(el, map.get(el) ? map.get(el) + 1 : 1);

  return map;
}, new Map());

const common = [];

// Iterate over the map entries and keep only the ones that occur more than once - these would be the intersection of the 2 arrays.
for (entry of occurrenceMap) {
  const [key, val] = entry;

  if (val > 1) {
    common.push(key);
  }
}


console.log(common);
Tom O.
  • 5,730
  • 2
  • 21
  • 35