I've solved the problem below by using a nested for loop, with the some() and startsWith() methods. Is there a way to solve this using filter() instead? Thanks in advance!
Write the function detectNetwork. It should accept a string or a number for its cardNumber argument, and should return the appropriate network string (or undefined if there's no match), based on the provided cardData.
//cardData array provided by the question
var cardData = [{
network: 'Visa', // card issuer (network)
prefixes: ['4'], // beginning digits
lengths: [13, 16, 19] // lengths of card numbers
}, {
network: 'Mastercard',
prefixes: ['51', '52', '53', '54', '55'],
lengths: [16]
}, {
network: 'American Express',
prefixes: ['34', '37'],
lengths: [15]
}, {
network: 'Diner\'s Club',
prefixes: ['38', '39'],
lengths: [14]
}];
//MY SOLUTION
function detectNetwork(cardNumber, cardData) {
//convert cardNumber into a String type
cardNumber = String(cardNumber);
//For each network, check if one of its prefix values matches to the prefix of cardNumber. If so, check if one of its lengths matches to the length of cardNumber.
for (let network of cardData) {
if (network['prefixes'].some(n => cardNumber.startsWith(n))) {
if (network['lengths'].some(n => cardNumber.length === n)) {
return network['network'];
}
}
}
//If no match, return undefined
return;
}