Loolii
Loolii

Reputation: 455

after using filter method, returned a one array

function test5(arr) {
    let age = arr.sort(function(a, b) {
        return Object.fromEntries(a).age - Object.fromEntries(b).age
    }); 
    
    // Arrange by young age. it's work well.
    
    let result = [];
    let name = age.filter (function (el) {
         if(Array.isArray(age[el])){
           result.push(firstName.concat(lastName));
         }
         return result;
     });
    return name
}

but bottom function doesn't work.. can't recognized 'age' array... so happend error.. I don't know why..

i wanna make like that,

const avengers = [
      [
        ['firstName', 'Captain'],
        ['lastName', 'Americano'],
        ['age', 105],
      ],
      [
        ['firstName', 'Master'],
        ['lastName', 'Strange'],
        ['age', 120],
      ],
      [
        ['firstName', 'IronyMan'],
        ['age', 55],
      ]
    ]


test5(list);
// -> ['IronyMan','Captain Americano', 'Master Strange']

Upvotes: 1

Views: 63

Answers (2)

Aalexander
Aalexander

Reputation: 5004

Here is a solution for this what you have tried.

  • First I rearranged your file structure to an array of objectss with the properties firstName, lastName and age
  • then I sort this array by the ages of the object in ascending order
  • In the last step I pushed the name(first name last name) in an result array and return this result array.

I check if the lastName and firstName property exists in this object. Because otherwise you would get for your Ironman the result "IronMan undefined" because he has no lastName

const avengers = [{
    firstName: 'Captain',
    lastName: 'Americano',
    age: 105,
  },
  {
    firstName: 'Master',
    lastName: 'Strange',
    age: 120
  },
  {
    firstName: 'IronyMan',
    age: 55
  }
]


console.log(test5(avengers));
// -> ['IronyMan','Captain Americano', 'Master Strange']


function test5(arr) {
  let result = [];



  let sortedByAge = arr.sort(compare);

  sortedByAge.forEach((x) => {
  let name = "";
  if(x.firstName !== undefined){
      name += x.firstName;
  }
  if(x.lastName !== undefined){
      name += " " + x.lastName;
  }
    result.push(name)
  })

  return result;
}

function compare(a, b) {
  return a.age - b.age;
}

Upvotes: 1

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11001

as @Alex pointed out, Use sort (based on age) and map to extract the name.

const process = (data) =>
  data
    .sort((a, b) => a[a.length - 1][1] - b[b.length - 1][1])
    .map((arr) =>
      arr
        .slice(0, arr.length - 1)
        .map(([, name]) => name)
        .join(" ")
    );

const avengers = [
  [
    ["firstName", "Captain"],
    ["lastName", "Americano"],
    ["age", 105],
  ],
  [
    ["firstName", "Master"],
    ["lastName", "Strange"],
    ["age", 120],
  ],
  [
    ["firstName", "IronyMan"],
    ["age", 55],
  ],
];

console.log(process(avengers))

Upvotes: 1

Related Questions