I am learning Java Script because I would like to become Tester.
This is a code that I wrote to sort elements from list which contains numbers and string and push them to another lists.
const table = [1,5,55,23,645,'Arek','Hermiona','Tomek','Irena'];
const tableOfNumbers = [];
const tableOfNames = [];
table.map(elementsPuller => {
if( typeof(elementsPuller) == String) {
tableOfNames.push(elementsPuller)
} else {
tableOfNumbers.push(elementsPuller)
}
})
console.log(`Names elements: ${tableOfNames}`)
console.log(`List elements: ${tableOfNumbers}`)
Output is :
Names elements:
List elements: 1,5,55,23,645,Arek,Hermiona,Tomek,Irena
Should be:
Names elements: Arek,Hermiona,Tomek,Irena
List elements: 1,5,55,23,645,
I spent hour to get it working and nothing.
4
Answers
The
typeof
operator returns the string.You could take an object with type as key and push directly.
Your iteration with
map
is returning an array, but you do not need this.With
Object.groupBy
and destructuring.so the correct code would look something like this:
Here is a reduce – having an object as accumulator
or reduce where we save ALL types of elements using a Nullish_coalescing_assignment ( the
??=
) to create an array per passed type.