What is the best way to arrange objects within an array based on a specific element contained in another array of objects?

Suppose we have two arrays of objects named per and con. The goal is to sort the per array in ascending order based on the continent values from the con array. How can we achieve this? By using the sort and find functions exclusively. Below is the code snippet:

function checkContinent(pe, co) {
  const cc = pe.sort(function(a) {
    let fa = co.find(function(b) {
      return b.city === a.city;
    });
    fa.sort(sortContAsc);
    return fa;
  });
  return cc;
}

function sortContAsc(s1, s2) {
  return s1.continent.localeCompare(s2.continent);
}

const per = [{
    name: "Mary",
    city: "London"
  },
  {
    name: "Anita",
    city: "Paris"
  },
  {
    name: "Edward",
    city: "New York"
  },
  {
    name: "Thomas",
    city: "Rome"
  },
  {
    name: "Robin",
    city: "Seattle"
  },
  {
    name: "Sophia",
    city: "Los Angeles"
  },
  {
    name: "Bruce",
    city: "Delhi"
  }
];

const con = [{
    city: "London",
    continent: "Europe"
  },
  {
    city: "Delhi",
    continent: "Asia"
  },
  {
    city: "Seattle",
    continent: "North America"
  },
  {
    city: "Paris",
    continent: "Europe"
  },
  {
    city: "New York",
    continent: "North America"
  },
  {
    city: "Rome",
    continent: "Europe"
  },
  {
    city: "Bengaluru",
    continent: "Asia"
  },
  {
    city: "Los Angeles",
    continent: "North America"
  }
];

const cs = con.sort(sortContAsc);

console.log(checkContinent(per, cs));

Answer №1

If you want to group the objects by continents based on the cities they belong to, consider this approach:

const
    people = [{ name: "Mary", city: "London" }, { name: "Anita", city: "Paris" }, { name: "Edward", city: "New York" }, { name: "Thomas", city: "Rome" }, { name: "Robin", city: "Seattle" }, { name: "Sophia", city: "Los Angeles" }, { name: "Bruce", city: "Delhi" }],
    continentsData = [{ city: "London", continent: "Europe" }, { city: "Delhi", continent: "Asia" }, { city: "Seattle", continent: "North America" }, { city: "Paris", continent: "Europe" }, { city: "New York", continent: "North America" }, { city: "Rome", continent: "Europe" }, { city: "Bengaluru", continent: "Asia" }, { city: "Los Angeles", continent: "North America" }],
    continentsMapping = Object.fromEntries(continentsData.map(({ city, continent }) => [city, continent]));
    
people.sort((a, b) => continentsMapping[a.city].localeCompare(continentsMapping[b.city]));

console.log(people);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

Let's simplify this process with a method using Array.prototype.sort() and String.prototype.localeCompare()

If you need more information, check out the documentation on Mozilla Web Docs at this link

const per = [
  {name:"Mary", city:"London"},
  {name:"Anita", city:"Paris" },
  {name:"Edward", city:"New York"},
  {name:"Thomas", city:"Rome"},
  {name:"Robin", city:"Seattle"},
  {name:"Sophia", city:"Los Angeles"},
  {name:"Bruce", city:"Delhi"}
],
con = [
  {city:"London", continent:"Europe"},
  {city:"Delhi", continent:"Asia"},
  {city:"Seattle", continent:"North America"},
  {city:"Paris", continent:"Europe"},
  {city:"New York", continent:"North America"},
  {city:"Rome", continent:"Europe"},
  {city:"Bengaluru", continent:"Asia"},
  {city:"Los Angeles", continent:"North America"}
],
findContinent = (cityToFind) => con.find(({ city }) => city === cityToFind).continent,
sortCountriesByContinent = () => per.sort((a, b) => {
  return findContinent(a.city).localeCompare(findContinent(b.city));
});

console.log(sortCountriesByContinent());


An alternative approach is to merge properties from "con" into "per" for simplicity. The spread syntax makes it easy:

const per = [
  {name:"Mary", city:"London"},
  {name:"Anita", city:"Paris" },
  {name:"Edward", city:"New York"},
  {name:"Thomas", city:"Rome"},
  {name:"Robin", city:"Seattle"},
  {name:"Sophia", city:"Los Angeles"},
  {name:"Bruce", city:"Delhi"}
],
con = [
  {city:"London", continent:"Europe"},
  {city:"Delhi", continent:"Asia"},
  {city:"Seattle", continent:"North America"},
  {city:"Paris", continent:"Europe"},
  {city:"New York", continent:"North America"},
  {city:"Rome", continent:"Europe"},
  {city:"Bengaluru", continent:"Asia"},
  {city:"Los Angeles", continent:"North America"}
],
sortCountriesByContinent = () => per.map((data) => {
    return {
      ...con.find(({ city }) => city === data.city),
      ...data
    };
})
.sort((a, b) => a.continent.localeCompare(b.continent))
.map((data) => delete data.continent && data);

console.log(sortCountriesByContinent());

For merging properties of two JavaScript objects dynamically, refer to this resource

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

How can I select a checkbox dynamically during runtime?

I am working on a JavaScript code that needs to add the checked option to a checkbox if it has an id or value of 2 at runtime. I have tried the following code, but unfortunately, I am unable to check the checkbox. Do you have any ideas on how to solve th ...

Need help setting up a time-based query in Laravel? Here's how to schedule it!

I am currently using the following query to update a status value. public function updateStatus(Request $request) { $customer = Customer::findOrFail($request->user_id); $customer->status = $request->status; $customer->new_customer_s ...

Extract all objects from an array where a specific field contains an array

data:[ { id:1, tags:['TagA','TagB','TagC'] }, { id:2, tags:['TagB','TagD'] }, { id:3, tags:[&a ...

Changing the href attribute of a link element when it is clicked

Currently, I am in the process of developing a dynamic hyperlink that enables the downloading of an image fetched from the server. Below is the code snippet I have been working with: In HTML: <a class="btn" id="controlDownloadJPEG" download>Save & ...

Why is the `node-config` configuration undefined within a TypeScript Jest environment?

I have a TypeScript module that is functional in both development and production environments. It utilizes https://github.com/lorenwest/node-config. When I attempt to import it into Jest for testing purposes, I encounter an error suggesting that the config ...

What is the most efficient way to transfer sample code to the clipboard by simply clicking a button?

UPDATE START***** This question is unique and not a duplicate. Here is my revised code snippet: I am able to retrieve innerHTML but facing an issue with copying it. Can someone help me test this on jsFiddler? Here's the HTML code: <div id="mydiv ...

Activate the CSS on a click event using the onClick method

I am trying to implement a transition that triggers when clicking on a specific div element. Currently, the transition only occurs with the active css class. How can I achieve this effect by simply clicking on the div itself? I am using reactjs and believe ...

The issue with `Meteor` createContainer not rendering in React is causing trouble

I have been attempting to dynamically retrieve data from a mongo database, with the goal of updating the client side automatically whenever new data is inserted. Initially, I used Tracker.autorun in the main.js file within the client directory, and it su ...

Please only submit the form if the check box has been ticked

<div id="checkbox"> <input type="checkbox" id="1" name="1"/><br/> <input type="checkbox" id="2" name="2"/><br/> <input type="checkbox" id="3" name="3"/><br/> <input type="submit" value="Create"/> </div ...

Tips for adding elements to an angular $scope.array?

Currently, I am facing an issue that I cannot seem to pinpoint (most likely due to my limited expertise in AngularJS). In my HTML file, I have a basic ng-repeat set up like this: <ul> <li ng-repeat="fot in fotografia"><img src="{{fot.path ...

Injecting a controller into an AngularJS module within an anonymous function

As a newcomer to the world of javascript and just beginning to work with angular.js, I have a question. I'm wondering if there is a method for injecting a controller into a module that is declared within an anonymous function. This is how my code cu ...

designing a collection of objects inside a function in a software program

Could someone kindly explain how to create an array of objects within a function (apart from the main function)? Let's consider a hypothetical scenario... Imagine we have a program called TimeScheduler.cpp that uses the class Schedule.h (with its i ...

Structuring a Javascript project with a focus on component-based architecture

If I am following a component-based architecture and defining each component as an ES6 module, I organize all components in a /components folder. This folder is further divided into subfolders for grouped components. /js /components - header - ...

Creating a seamless scrolling experience with a designated stopping point - here's how to achieve it!

I understand how to implement a scroll effect on an element with a specific class or ID. However, I am unsure of how to make the scrolling stop 20px above that element. I have seen examples using document.getElementById() to achieve this: function scr ...

Adjusting the height of a flexbox column to fit three rows within the space of two

Exploring the wonders of Flexbox and delving into its functionality. I have shared a Code Sandbox link showcasing my React /bootstrap code in progress... Currently, I am developing a clock component with two buttons for adjusting time (increase/decrease). ...

Node.js is not accurately setting the content length. How can I resolve this issue?

I could use some assistance. Even though I have set the content-length on the response object, it doesn't seem to be working. Have I done something incorrectly? res.set({ 'Content-Type': res._data.ContentType, 'Content-Length' ...

Error: Unable to access the 'Result' property because it is undefined

I am encountering an issue while attempting to showcase database results, and the error message I'm receiving is: TypeError: Cannot read property 'Result' of undefined I am in the process of developing a Single Page Application with Angula ...

What steps are necessary to add a Contact Us form to my HTML website?

Currently, I am searching for a way to add a "Contact Us" section to my website that is completely HTML-based. I believe the best approach would involve using a PHP script to handle sending emails from a form on the Contact Us page, but I am not familiar ...

What is the simplest way to display an HTTP response in an alert window?

Struggling to display the JSON response using JavaScript's window.alert or alert. As a non-native JS coder, I apologize for my lack of experience. Here are a few attempts I've made based on online examples. My objective is to showcase the JSON r ...

Sharing an array between two sibling components

Within my 'Home' component, users have the ability to create QR codes. I have implemented a method that generates an array of these QR items. Now, the challenge lies in passing this array to another component that is a sibling and not located wit ...