So I want to create a function in js which takes two arrays and pare them and give a score depending on how many spots in the two arrays match. Is it right or it's bd written. I am new on coding.
Another problem I have is when I try to execute it on chrome's console. It says that pare is not defined
let score = 0;
function pare(arr1, arr2) {
for (let i = 0; i < arr2.length; i++) {
for (let j = 0; j < arr1.length; j++) {
if(arr1[j] === arr2[i]){
score++;
}
}
}
So I want to create a function in js which takes two arrays and pare them and give a score depending on how many spots in the two arrays match. Is it right or it's bd written. I am new on coding.
Another problem I have is when I try to execute it on chrome's console. It says that pare is not defined
let score = 0;
function pare(arr1, arr2) {
for (let i = 0; i < arr2.length; i++) {
for (let j = 0; j < arr1.length; j++) {
if(arr1[j] === arr2[i]){
score++;
}
}
}
Share
Improve this question
edited Apr 15, 2018 at 10:34
Mohammad Usman
39.4k20 gold badges98 silver badges99 bronze badges
asked Apr 15, 2018 at 10:09
Nil folquer covarrubiasNil folquer covarrubias
1391 gold badge2 silver badges7 bronze badges
2
-
Should multiple matches of one sport be counted as well. The score of
[1,2]
and[1,1,1,1,2,2,2,2]
should be 8? – Ori Drori Commented Apr 15, 2018 at 12:34 - I know I'm late to the party on this one, but the reason the function was defined was because you didn't have a closing bracket for the first for loop. ;-) – Jester Commented Jul 20, 2020 at 23:35
2 Answers
Reset to default 7You can use .reduce()
to find count of matched elements:
let arr1 = [1, 2, 3, 4, 5],
arr2 = [3, 4, 5, 6, 7],
pare = (a1, a2) => arr1.reduce((a, c) => a + arr2.includes(c), 0);
console.log(pare(arr1, arr2));
Alternatively, you can use .filter()
to find array of matched elements and use its length to determine the count.
let arr1 = [1, 2, 3, 4, 5],
arr2 = [3, 4, 5, 6, 7],
pare = (a1, a2) => arr1.filter(v => arr2.includes(v)).length;
console.log(pare(arr1, arr2));
Docs:
Array.prototype.reduce()
Array.prototype.includes()
Array.prototype.filter()
Arrow Functions
This should work for you:
Updated the code as required by you :
let arr1 = [1, 2, 3, 4];
let arr2 = [3,2,3,4,5];
function pare(arr1,arr2){
let count=0;
const max=arr1.length>arr2.length ? arr2.length : arr1.length;
for(var i=0;i<max;i++){
if(arr1[i]==arr2[i]){
count++;
}
}
return count;
}
console.log(pare(arr1,arr2));