I have a two arrays which contains repeated characters. I tried to achieve it by using for loop in JavaScript.
I am getting output with repeated and also non repeated. which is not expected. I want only repeated characters in two arrays.
Thanks in advance.
I have a two arrays which contains repeated characters. I tried to achieve it by using for loop in JavaScript. I am getting output with repeated and also non repeated. which is not expected. I want only repeated characters in two arrays.
let arr1 = [1, 1, 2, 2, 3, 3, 4];
let arr2 = [1, 1, 2, 2, 7, 3, 3, 5, 6, 1];
function repeatedElements(inputArray1, inputArray2) {
let repeatedEle = [];
for (let ele of inputArray1) {
if (inputArray1.indexOf(ele) !== inputArray2.lastIndexOf(ele)) {
repeatedEle.push(ele)
}
}
return [...new Set(repeatedEle)]
}
console.log(repeatedElements(arr1, arr2));
4
Answers
Change your for loop to this:
then return the array repeatedEle
You need to loop through each array separately and check if the element is present more than once and then you can use Set two get the unique elements out of it.
for the best efficient way, you can use loadsh [website][1]