I have two variables with numbers and I need to figure out which to know what parts are the same. I would like to do this even with more than just two strings if possible.
I could use (var1.indexOf(?) > -1 && var2.indexOf(?) > -1)
, but I'd have to cover every possible number. (or letter, if I wanted to compare strings)
If it helps in my specific case, these numbers coming from the following type of variable as an example:
const originalVar1 = [1,3,2,0,6]
const var1 = originalVar1.sort().join('');
const var1 = '01236';
const var2 = '12345';
let same = '';
for (let i = 0; i < 10; i++) {
same += (var1.indexOf(i) > -1 && var2.indexOf(i) > -1) ? `${i}` : '';
}
console.log(same); // Outputs: 123
My solution works but feels like there should be some built in function or method to do this already. Maybe my solution could be more elegant as it doesn't cover all characters.
Examples:
var1 = '01456'
var2 = '0246'
whatIsTheSame(var1, var2) // Expected output: 046
var1 = '12359'
var2 = '035679'
whatIsTheSame(var1, var2) // Expected output: 359
Another Solution
shash678 solution below works perfectly for getting 1 instance of every character that appears in every variable. The following solution gives you all instances of every character that appears in every variable.
value = [ '39291', '3902', '3039903', '39039311873', '3737298' ]
value.sort((a, b) => b.length - a.length);
let matches = value[0];
for (let i = 1; i < value.length; i++) {
matches = (matches.match(new RegExp(`[${value[i]}]`, 'g')) || []).join('');
}
console.log(matches); // Outputs: 393933
This is based on these answers here:
https://stackoverflow.com/a/51179953/11866303 Sort array by length
https://stackoverflow.com/a/41708135/11866303 Regex solution
It's possible this could be more elegant but I'm not the best. Thanks everyone.