skip to Main Content

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


  1. The typeof operator returns the string.

    The typeof operator returns a string indicating the type of the operand’s value.

    const table = [1, 5, 55, 23, 645, 'Arek', 'Hermiona', 'Tomek', 'Irena'];
    const tableOfNumbers = [];
    const tableOfNames = [];
    
    table.forEach(elementsPuller => {
      if (typeof elementsPuller === "string") {
        tableOfNames.push(elementsPuller)
      } else {
        tableOfNumbers.push(elementsPuller)
      }
    })
    
    console.log(`Names elements: ${tableOfNames}`)
    
    console.log(`List elements: ${tableOfNumbers}`)
    Login or Signup to reply.
  2. 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.

    const
        table = [1, 5, 55, 23, 645, 'Arek', 'Hermiona', 'Tomek', 'Irena'],
        tableOfNumbers = [],
        tableOfNames = [],
        types = { string: tableOfNames, number: tableOfNumbers };
    
    for (const elementsPuller of table) 
        types[typeof elementsPuller]?.push(elementsPuller);
    
    console.log(`Names elements: ${tableOfNames}`);
    console.log(`List elements: ${tableOfNumbers}`);

    With Object.groupBy and destructuring.

    const
        table = [1, 5, 55, 23, 645, 'Arek', 'Hermiona', 'Tomek', 'Irena'],
        { string: tableOfNames, number: tableOfNumbers } = Object.groupBy(table, v => typeof v);
    
    console.log(`Names elements: ${tableOfNames}`);
    console.log(`List elements: ${tableOfNumbers}`);
    Login or Signup to reply.
    1. The map() method of Array instances creates a new array populated with the results of calling a provided function on every element in the calling array. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map, so it is not the correct method here. What you want is arr.forEach(); https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
    2. you need to use the strict equals operator ( === );
    3. typeof "a" returns "string" not String;
    4. a nitpick, but elementsPuller is a weird name, ‘item’ or ‘tableItem’ sounds better imo;

    so the correct code would look something like this:

    const table = [1,5,55,23,645,'Arek','Hermiona','Tomek','Irena'];
    const tableOfNumbers = [];
    const tableOfNames = [];
    
    
    table.forEach(item => {
        if( typeof item === "string") {
            tableOfNames.push(item)
        } else { 
            tableOfNumbers.push(item)
        }
    })
    
    console.log(`Names elements: ${tableOfNames}`)
    console.log(`List elements: ${tableOfNumbers}`)
    Login or Signup to reply.
  3. Here is a reduce – having an object as accumulator

    const table = [1, 5, 55, 23, 645, 'Arek', 'Hermiona', 'Tomek', 'Irena'],
      types = table
        .reduce((acc, element) => (acc[typeof element].push(element), acc), {string: [],number: []})
    
    console.log(`Strings: ${types.string}`)
    console.log(`Numbers: ${types.number}`)

    or reduce where we save ALL types of elements using a Nullish_coalescing_assignment ( the ??=) to create an array per passed type.

    const table = [1, 5, 55, 23, 645, 
    'Arek', 'Hermiona', 'Tomek', 'Irena', 
    ["a","b","c"], () => alert('Hello')
    ];
    const types = table
      .reduce((acc, element) => {
    acc[typeof element] ??= []; // nullish coalescing assignment
    acc[typeof element].push(element);
    return acc ;
      },{});
    
    Object.entries(types)
      .forEach(([key,value]) => console.log(`${key}: ${key === 'object' ? 
        JSON.stringify(value[0]) : value}`)
      );
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search