how can i solve this exercise with array methods?

Hi guys and sorry for my english. I have this array of objects and I need to get an input like: {name: Karen, age: 12} -> Karen-12.

How can I do it?

This is the exercise:

function nicknameMap(p) {
  
}

const p = [
  { name: 'ninny', age: 19},
  { name: 'albert', age: 20},
  { name: 'daniel', age: 60},
  { name: 'bob', age: 20},
  { name: 'wilfred', age: 40},
  { name: 'rob', age: 22},
  { name: 'gary', age: 9},
  { name: 'robin', age: 19},
  { name: 'carl', age: 43 },
  { name: 'v', age: 82 }
];

const nicknames = nicknameMap(p);
console.log(p);
console.log(nicknames);``` 

3 answers

  • answered 2022-01-13 04:53 amlxv

    function nicknameMap(p) {
      let result = Array();
      p.forEach((n) => {
        result.push(`${n.name}-${n.age}`);
      });
      return result;
    }
    

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

  • answered 2022-01-13 04:53 Ryan Baker

    It's best to learn by yourself, but I'm assuming you've had a crack at it and are asking because you have run out of options.

    EDIT: amlxv solution is a more "Javascript" way of doing it, and is technically more correct than mine.

    Below is a solution to your problem.

    function nicknameMap(p) {
        let arr = [];
        
        for(let i = 0; i<p.length; i++){
          arr.push(p[i].name + "-" + p[i].age);
        }
        
        return arr;
    }
    
    const p = [
      { name: 'ninny', age: 19},
      { name: 'albert', age: 20},
      { name: 'daniel', age: 60},
      { name: 'bob', age: 20},
      { name: 'wilfred', age: 40},
      { name: 'rob', age: 22},
      { name: 'gary', age: 9},
      { name: 'robin', age: 19},
      { name: 'carl', age: 43 },
      { name: 'v', age: 82 }
    ];
    
    const nicknames = nicknameMap(p);
    console.log(p);
    console.log(nicknames);
    

  • answered 2022-01-13 05:03 PeterKA

    Use the .map() array method as follows:

    function nicknameMap(p) {
        return p.map(({name,age}) => `${name}-${age}`);
    }
    //output
    //[
    //  "ninny-19",
    //  "albert-20",
    //  "daniel-60",
    //  "bob-20",
    //  .....
    //]
    

    function nicknameMap(p) {
        return p.map(({name,age}) => `${name}-${age}`);
    }
    
    const p = [
      { name: 'ninny', age: 19},
      { name: 'albert', age: 20},
      { name: 'daniel', age: 60},
      { name: 'bob', age: 20},
      { name: 'wilfred', age: 40},
      { name: 'rob', age: 22},
      { name: 'gary', age: 9},
      { name: 'robin', age: 19},
      { name: 'carl', age: 43 },
      { name: 'v', age: 82 }
    ];
    
    const nicknames = nicknameMap(p);
    console.log(p);
    console.log(nicknames);

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum