function checkTwice(theNum) {
const arr = [12,65,31,26,13,51,26,12,51];
const newArray = arr.filter( x => x === theNum);
return theNum + ' found ' + newArray.length + ' times!';
}
console.log ( checkTwice ( 12 ) );
This will tell you exactly how many times a given arg is found in the array. If you only want to know if a number is found exactly twice (and not say, once or three times etc), just do this:
return (newArray.length === 2 ? theNum + ' found twice!' : theNum + ' not found twice, it was found ' + newArray.length + ' times!';
If you need to do this without feeding the function an arg, and just want to list out the numbers in the array that appear twice or more (again, if only twice, the modification would be the same as above):
function checkTwice() {
const arr = [12,65,31,26,13,51,26,12,51];
const found = [];
arr.forEach ( x => {
const test = arr.filter ( y => x === y );
if (test.length > 1) {
found.push ( x );
}
});
return ( found.length ? 'The following numbers were found more than once: ' + found.join( ',' ) : 'No numbers in the array were found more than once.');
}
Following up on your comment, if you want to check one array against another:
const arrayToCheck = [12,15];
function checkTwice(arrayToCheck) {
const arr = [12,65,31,26,13,51,26,12,51];
const found = [];
arrayToCheck.forEach( x => {
const test = arr.filter( y => x === y);
if ( test.length > 1 ) {
found.push ( x );
}
});
return ( found.length ? 'The following numbers were found more than once: ' + found.join( ',' ) : 'No numbers in the array were found more than once.');
}