Intermediate Algorithm Scripting - Diff Two Arrays

Tell us what’s happening:

Example Array:
The variable “findSingleInstances” is the following array:
[ ‘1’, ‘3’, ‘7’, ‘calf’, ‘piglet’, ‘filly’ ]

I want to change ‘1’, ‘3’, and ‘7’ from strings to numbers
I want to keep ‘calf’, ‘piglet’ and ‘filly’ as strings

My thought process is to map this array with the following condition:
if I were to use Number() to turn the value into a number and it does NOT result in NaN, then push the following to the finalArr:

finalArr.push(Number(value))

Otherwise, just push the original value to the finalArr:

finalArr.push(value)

Currently I get [ 1, 3, 7, NaN, NaN, NaN ] as my result
If I were to change the boolean to the opposite then I get the original array unchanged

I am not sure why the strings are being converted to numbers despite not passing the condition I set?

Your code so far

 let finalArr = [];

  let findSingleInstances = Object.keys(counter);

  findSingleInstances.map(value => {
    if (Number(value) !== NaN) finalArr.push(Number(value))
    else finalArr.push(value);
    return finalArr;
  });

  console.log(finalArr)
  return finalArr;

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36

Challenge Information:

Intermediate Algorithm Scripting - Diff Two Arrays

This approach with comparing to NaN will not work:

console.log(NaN == NaN)   // false
console.log(NaN === NaN)  // false
console.log(NaN != NaN)   // true
console.log(NaN !== NaN)  // true

Use isNaN function for this:

console.log(isNaN(NaN))           // true
console.log(isNaN(Number('4')))   // false
console.log(isNaN(Number('text')) // true
1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.