Trying to loop through second array to see if the first array have a match, where there is match then the index of the second array(or a new array) will contain the number of each time to element was found and it will display it in a new array:
function getOccur(ar1, ar2){
let ar = [];
return ar2.filter((el,i)=>ar2.includes((el)=>{
ar[i]+= 1;
}));
return ar;
}
getOccur(
['apple', 'orange', 'apple', 'pp', 'pear', 'orange'],
['apple', 'orange', 'pear', 'banana']
);
The output I want is:
[2, 2, 1, 0]
That is, apple occurs 2 times, orange occurs 2 times, pear occurs 1 time and banana occurs 0 times
How about looping the 2nd array, and count how many times each item is present in the first array using filter? In that way, you can remove the includes and code is much easier to understand.
function getOccur(arr1, arr2) {
let finalArr = [];
arr2.forEach((a) => {
finalArr.push(arr1.filter(item => item === a).length);
});
return finalArr;
}
const arr1 = ['apple', 'orange', 'apple', 'pp', 'pear', 'orange'];
const arr2 = ['apple', 'orange', 'pear', 'banana'];
console.log(getOccur(arr1, arr2));
You need to count up the number of occurances - includes will only give you true or false, and filter will only give you a filtered version of the original array. Neither of those are all that appropriate for this situation - I'd use reduce instead, for an O(n) solution:
const getOccur = (ar1, ar2) => Object.values(
ar1.reduce(
(a, item) => {
if (item in a) a[item]++;
return a;
},
ar2.reduce((a, prop) => {
a[prop] = 0;
return a;
}, {})
)
);
console.log(
getOccur(
['apple', 'orange', 'apple', 'pp', 'pear', 'orange'],
['apple', 'orange', 'pear', 'banana']
)
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With