0

As a result of below code, I am wanting to return only unique values. As an example, if there are three 'Company not found' items that will be returned in the array, I would like it to be written only once. Can anyone help?

function findInvalidCardCompanies(invalidCards) {
const invalidCompany=[];

for (let j=0; j<invalidCards.length; j++) {
let inv=invalidCards[j];
if(inv[1]===3) {invalidCompany.push('Amex')}
else if (inv[1]===4) {invalidCompany.push('Visa')}
else if (inv[1]===5) {invalidCompany.push ('Mastercard')}
else if (inv[1]===6) {invalidCompany.push('Discover')}
else {invalidCompany.push('Company not found')};
}
return invalidCompany;
};
console.log(findInvalidCardCompanies(findInvalidCards(batch)));
B_12
  • 143
  • 1
  • 9
  • https://stackoverflow.com/questions/1960473/get-all-unique-values-in-a-javascript-array-remove-duplicates – WillD Apr 19 '20 at 19:21
  • @WillD I saw it but couldn't figure out how to implement into my code above. – B_12 Apr 19 '20 at 19:24

2 Answers2

2

Use the javascript Set Object to remove the duplicate items. The Set object lets you store unique values of any type, whether primitive values or object references. More details here

 // Use to remove duplicate elements from the array 

const numbers = [2,3,4,4,2,3,3,4,4,5,5,6,6,7,5,32,3,4,5]

console.log([...new Set(numbers)]) 

// [2, 3, 4, 5, 6, 7, 32]

So your function will look something like this:

function findInvalidCardCompanies(invalidCards) {
const invalidCompany=[];

for (let j=0; j<invalidCards.length; j++) {
let inv=invalidCards[j];
if(inv[1]===3) {invalidCompany.push('Amex')}
else if (inv[1]===4) {invalidCompany.push('Visa')}
else if (inv[1]===5) {invalidCompany.push ('Mastercard')}
else if (inv[1]===6) {invalidCompany.push('Discover')}
else {invalidCompany.push('Company not found')};
}
return [...new Set(invalidCompany)];
};
console.log(findInvalidCardCompanies(findInvalidCards(batch)));
Saadi
  • 1,292
  • 13
  • 22
  • If I wanted to use if (invalidCompany.indexOf('Mastercard') === -1), what would be the best way to add it to code? Especially for the 'Company not found' part. – B_12 Apr 19 '20 at 19:46
0

Use a Set. A value in the Set may only occur once; it is unique in the Set's collection.

You can add to a set with the add Function. If you add an already existing value, it will be ignored.

function findInvalidCardCompanies(invalidCards) {
const invalidCompany= new Set();

for (let j=0; j<invalidCards.length; j++) {
let inv=invalidCards[j];
if(inv[1]===3) {invalidCompany.add('Amex')}
else if (inv[1]===4) {invalidCompany.add('Visa')}
else if (inv[1]===5) {invalidCompany.add ('Mastercard')}
else if (inv[1]===6) {invalidCompany.add('Discover')}
else {invalidCompany.add('Company not found')};
}
return invalidCompany;
};
console.log(findInvalidCardCompanies(findInvalidCards(batch)));
Gh05d
  • 7,923
  • 7
  • 33
  • 64