Arrange the names in ascending order within arrays in an array

If we consider a scenario where an array of names is provided,

let names = [
  [
    ['firstName', 'Rachel'],
    ['age', 10],
    ['gender', 'female'],
  ],
  [
    ['firstName', 'Sam'],
    ['lastName', 'Smith'],
    ['age', 20],
    ['gender', 'male'],
  ],
];

The desired output would resemble the code snippet below.

let output = nameInOrder(names);
console.log(output); // --> ['Rachel', 'Sam Smith'];

In order to successfully implement the nameInOrder function,

function nameInOrder(arr) {
// insert code here
}

Would it be appropriate to start with the .map method for transforming the data into objects within an array, then utilize sort(a,b) and .join(' ')? How should they be sorted in ascending order?

Answer №1

.map is a step in the right direction for data transformation and sorting.

let members = [
  [
    ['name', 'Alice'],
    ['age', 30],
    ['gender', 'female'],
  ],
  [
    ['name', 'Bob'],
    ['lastName', 'Johnson'],
    ['age', 25],
    ['gender', 'male'],
  ],
];

function sortNames(arr) {
  return arr.map(member => {
    const attributes = member.map(info => info[0])
    if (attributes.includes('name') && attributes.includes('lastName')) {
      return [
        member.find(info => info[0] == 'name')[1],
        member.find(info => info[0] == 'lastName')[1],
      ].join(' ')
    } else if (attributes.includes('name')) {
      return member.find(info => info[0] == 'name')[1]
    } else if (attributes.includes('lastName')) {
      return member.find(info => info[1] == 'lastName')[1]
    } else {
      return ''
    }
  }).sort()
}

console.log(sortNames(members))

Answer №2

If you want to sort names in JavaScript arrays, you can utilize the .sort() method by referring to the documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort.

Create a function that compares the names when using .sort().

names.sort((a,b) => {
  var nameA = a[0][1].toUpperCase(); // disregard case sensitivity
  var nameB = b[0][1].toUpperCase(); // disregard case sensitivity
  if (nameA < nameB) {
    return -1;
  }
  if (nameA > nameB) {
    return 1;
  }

  // names are equal
  return 0;
});

It is recommended not to structure your data like this and instead consider the following format:

let names = [
  [
    { 'firstName': 'Rachel' },
    { 'age': 10 },
    { 'gender': 'female' }
  ]
];

In this format, sorting can still be done similarly without depending on the attribute order in the array of names.

names.sort((a,b) => {
  var nameA = a.firstName.toUpperCase(); // ignore case sensitivity
  var nameB = b.firstName.toUpperCase(); // ignore case sensitivity
  if (nameA < nameB) {
    return -1;
  }
  if (nameA > nameB) {
    return 1;
  }

  // names are equal
  return 0;
});

Answer №3

If the data source is limited to arrays only.

const items = [
  [
    ['itemName', 'Apple'],
    ['price', 1.50],
    ['category', 'fruit'],
  ],
  [
    ['itemName', 'Banana'],
    ['price', 0.75],
    ['category', 'fruit'],
  ],
];

const result = items.map(item => {
    const details = item.reduce((obj, [key, value]) => {
        obj[key] = value;
        return obj;
      }, {});
    return `${details.itemName || ''} - $${details.price || ''}`.trim();
});

console.log(result);

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 specified subpath './lib/tokenize' does not match any defined "exports"

As a newcomer to React, I've been facing some challenges while trying to get started. Despite searching on Google and other platforms, I couldn't find a solution to my problem. I was attempting to run code from a YouTube channel called Lama Dev b ...

Creating a dynamic array of arrays in JavaScript can be achieved by initializing an empty array

Currently, I am retrieving data and populating a two-dimensional array using the code below with an initialized 2D array called "series." The structure of "series" is as follows (Highchart series): series: [{ name: '', data: [] ...

Using a pointer to reference an array of integers and calculating the sum

After being tasked with creating a function Adder() that takes in a pointer to an integer array and returns the sum of its elements, I successfully wrote the code: #include <bits/stdc++.h> using namespace std; int Adder (int *ptr) { int sum ...

Cannot access console.log within Angular UI Router .config()=> {}

I've been working on connecting different parts of a basic Angular application, but I'm facing an issue where my initial view state is not loading. A major problem seems to be that I am unable to log inside the .config set up (even though I have ...

Top method for creating 12 dynamic product pages using AngularJS with customized routing and templates

As someone who is still relatively new to AngularJS, I am looking for advice on how to properly structure the products section of my application. My main product page will display all 12 products with clickable links to individual product pages. Each indi ...

Invoking a static method within a cshtml document

I am currently working on implementing a clickable DIV within a vertical tab panel. My goal is to have a specific static method called when the DIV is clicked. Here is what I have done: <div class="tabbable tabs-left"> <ul class="nav nav-tabs"> ...

Is there a way to access a globally defined AJAX variable?

I'm facing a challenge with accessing a variable that I created within an AJAX success function for use in another AJAX call outside of that function. I attempted to store the variable using local storage, but encountered difficulties in accessing it. ...

Developing a unique note-taking solution by leveraging JQuery mobile and phone gap technology

I am currently working on an app using JQ Mobile and PhoneGap. One feature that I would like to implement is a 'Notes Taking' page with the following functionalities: Create new notes and save them locally Retrieve notes whenever needed Edit an ...

Adding items to a mongoose array field using values from an array | Interaction with MongoDB Mongoose

I'm a bit confused about how to push all objects from an array into a mongoose array field. Do I need to use a loop? I've created an inventory model where "itemlist" is an array within the item schema field const itemListSchema: mongoose.Schema ...

Error encountered during sequelize synchronization: SQL syntax issue detected near the specified number

Four Sequelize Models were created using sequelize.define();. Each model is similar but with different table names. To avoid manual creation of tables in MySQL cli, the decision was made to use sequelize.sync() in the main index.js file to allow Sequelize ...

Using localStorage in Next.js, Redux, and TypeScript may lead to errors as it is not defined

Currently, I am encountering an issue in my project where I am receiving a ReferenceError: localStorage is not defined. The technologies I am using for this project are Nextjs, Redux, and Typescript. https://i.stack.imgur.com/6l3vs.png I have declared ...

The parameter 'prevState: Stock[]' does not match the expected type 'SetStateAction<Stock[] | []>'

I'm currently diving into TypeScript and I encountered the following error message that has me stumped. Interestingly, the code runs smoothly without TypeScript. Can anyone provide guidance on how to resolve this issue? Error details: Argument of typ ...

In IE7 specifically, JQuery causes all scripts on the page to malfunction

After adding this script, all jQuery functionalities on the page stopped working only in IE7. Removing the script resolved the issue and everything started functioning properly again. function go_standards() { var audit_id = $('#auditID' ...

Create an SVG timeline representation

I am attempting to create a circular timeline using SVG. I am utilizing fullpage js for this purpose. I have successfully implemented a blue line that progresses around the circle as the user scrolls. Now, I am looking to make my anchors dash array visible ...

Why is 'this.contains' not recognized as a function when I invoke it within another function?

While attempting to create a Graph and incorporating one method at a time, I encountered an issue. Specifically, after calling a.contains("cats"), I received the error '//TypeError: Cannot read property 'length' of undefined'. Could thi ...

A comprehensive guide on associating a JavaScript function with an element attribute

I am looking for a way to assign a JavaScript function to an HTML attribute. For example: <li data-ng-repeat="job in jobList" class= dynamicClass(str) data-filter = "dynamicFilter(str)"> The reason I want to do this is because the class name and ...

What is the functionality behind app.listen() and app.get() in Hapi.js, Restify, and Koa?

Using the http node module, which consists of only native modules, how can I create a custom version of app.listen() and app.get() by utilizing the http module with a constructor? var app = function(opts) { this.token= opts.token } app.prototype ...

I am interested in changing the sitecore search facet filter from allowing multiple selections to only allowing a single

I have successfully implemented the Sitecore search widget and the result list is working as expected. However, I encountered an issue with the filter functionality using facets. By default, it supports multiple filters but my requirement is to have singl ...

PHP script for executing commands in a sequential order

Can anyone help me with writing a script that will run commands sequentially, one after the other, waiting for each to finish before starting the next? php bin/console SOME:CUSTOM:COMMAND <PART_1_ARGUMENT> <PART_2_ARGUMENT> --env=xxx I have ...

Selecting items using raycasting

Currently attempting to select objects when clicked, using the common code found in various examples: function onMouseDown(evt) { evt.preventDefault(); canvasAbsoluteHeight = $('canvas').height(); canvasAbsoluteWidth = $('canv ...