Following the application of the filter function, a singular array was generated as the output

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

However, the bottom function is not working. It cannot recognize the 'age' array, which causes an error. I am unsure why this happens.

I want to achieve something like this:

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


sortByAge(avengers);
// -> ['IronyMan','Captain Americano', 'Master Strange']

Answer №1

Providing a solution to the challenge you're facing, here's what I suggest:

  • I began by restructuring your file layout into an array of objects with properties such as firstName, lastName, and age.
  • Next, I arranged this array in ascending order based on the ages of the objects.
  • Lastly, I extracted the name (first name followed by last name) and stored it in a result array before returning this array.

It's essential to verify if both the lastName and firstName properties exist within the object. Otherwise, there might be discrepancies like receiving "IronMan undefined" since IronMan lacks a lastName property.

const heroes = [{
    firstName: 'Black',
    lastName: 'Widow',
    age: 35,
  },
  {
    firstName: 'Hulk',
    lastName: 'Smash',
    age: 42
  },
  {
    firstName: 'Thor',
    age: 150
  }
]


console.log(getSortedNames(heroes));
// -> ['Thor', 'Black Widow', 'Hulk Smash']


function getSortedNames(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;
}

Answer №2

as @Alex already mentioned, you can utilize the sort method (sorting by age) along with the map function to extract the names.

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))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The object for checking Ajax connections is not providing any values

I've been working on creating a unique AJAX connection check object, but unfortunately I'm struggling to get it to function properly. :/ Here's the object structure: function Connection(data){ this.isConnected = false, this.check = funct ...

Encountering the error "Cannot read property 'header' of undefined" while conducting tests on Nodejs using supertest

In my server.js file, I have set up my express app. I tried to run a demo test in my test file using express, but unfortunately, the test did not run successfully. const request = require('supertest'); const express = require('express' ...

Embedding a YouTube video in an iframe triggers numerous cautionary notifications in the Chrome browser

I have a website with numerous YouTube links embedded in iframes. However, the page loads extremely slowly and some of the YouTube images do not load at all. The website is built using PHP. Even with just 7 YouTube links, the Chrome browser generates over ...

Ways to convert a PHP array into a JavaScript array

I have a 3D array in php when using var_dump($arr) it looks like this array(2) { [0]=> array(4) { [0]=> array(2) { [0]=> string(7) "36.3636" [1]=> int(8) } [1]=> array(2) { [0]=> string(7) "27.2727" [1]=> int(5) } [2]=> a ...

What is the best way to transform arrays like this into a JSON object?

Below is an array that I need to convert into an object: [ [ '560134275538747403', 39953 ], [ '411510958020624384', 36164 ], [ '468512396948930576', 31762 ], [ '482286641982078977', 29434 ], ...

What is the process for selectively adding interceptors to app.module?

After searching through various topics, I have not found a solution that addresses my specific issue. To provide some context, we have an Angular App that operates in two modes - one mode uses one API while the other mode utilizes a different API. My goal ...

Vuex - modify store state without changing the original object

Currently, I am encountering an issue where my attempt to duplicate a store object for local modification is causing the original store object to also be changed. The specific method I am using is ...mapState["storeObject"] To illustrate, here is a breakd ...

Creating multiple tables in an HTML template using loops, either with or without JavaScript, each table identical to the one previously created

<html> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3. ...

Updating a React event as it changes with each onChange event

Let's address a disclaimer before diving into the issue - for a quick look, visit this pen and type something there. The Scenario This is the JSX code snippet used in my render method: <input value={this.state.value} onChange={this.handleCh ...

Searching for identical consecutive numbers in a grid

Hi there, I'm currently working on developing a function that can detect if a N*N matrix contains at least two adjacent numbers (ranging from 0 to h-1) in the up-down-left-right directions. The function should return 1 if such numbers are found, and 0 ...

React Router is not compatible with ReactJS app version 18

After using the command npx create-react-app, I've just set up a new ReactJS app which I think is running on React version 18 (feel free to correct me if I'm mistaken). Now, as I attempt to implement a router for this app, I find myself hesitati ...

Change the output of Object.fromEntries

I've been working on updating the values of an object using the .fromEntries() method. The issue I am facing is that even though I am returning a modified Array of hours, when the function completes it reverts back to the original complete Array. If ...

Can a C# MVC List<int> be transformed into a JavaScript array?

Can a MVC C# List be converted to a JavaScript array? var jsArray = @Model.IntList; I would really appreciate any assistance on this matter. ...

I am having trouble retrieving any data when using jQuery to post JSON data

I am struggling with some HTML and JavaScript code. Here is what I have: <html> <head> </head> <body> <script src="view/backoffice/assets/plugins/jquery/jquery-1.11.1.min.js" type="text/javascript"></sc ...

Can a faulty image be cached?

Is there a way to ensure that the browser caches invalid or broken images so that when they are re-fetched, the loading time is immediate? I am particularly interested in two scenarios: 1) The first scenario involves trying to load an image from a URL co ...

Tips for selecting specific types from a list using generic types in TypeScript

Can anyone assist me in creating a function that retrieves all instances of a specified type from a list of candidates, each of which is derived from a shared parent class? For example, I attempted the following code: class A { p ...

Difficulty arises when collapsed text in Bootstrap clashes with the footer design

Hey there! I'm working on this website using Bootstrap, and I've encountered a problem. When you click the "See Wikipedia" button, the content expands and overlaps the footer in a strange way without changing the page height. I've tried adju ...

Improving basic collision detection using velocity-based 2D motion

Check out this CodePen demo where you can control the movement of the "player" square using arrow keys. You can also place a light by pressing the spacebar and the player is supposed to be prevented from crossing over the blue lines by getting pushed in ...

Infinite scrolling made effortless with jQuery and Ajax

I am attempting to create a basic infinite scroll feature that monitors when the user scrolls to the bottom in an HTML file. Once the bottom is reached, it should then load additional content from another HTML file which contains more text. The second HTM ...

What is the best way to set the date defaultValue to be empty?

I've developed a basic radio button to display an additional input field when the user chooses yes. I also created a function that will clear the fields if the user selects no. schema.ts: const formSchemaData = z.object({ doesHaveDryRun: z.enum( ...