Using Javascript to organize an array of objects based on a specific condition

Having an array of objects structured as follows:

obj = [{'name': 'Tom', 'age': 17, 'gender': 'male', 'color':'red', 'position':3},
        {'name': 'Sam', 'age': 19, 'gender': 'male', 'color':'red', 'position':2},
        {'name': 'Harry', 'age': 16, 'gender': 'male', 'color':'red', 'position':1},
        {'name': 'Charles', 'age': 19, 'gender': 'male', 'color':'blue', 'position':2},
        {'name': 'Fred', 'age': 21, 'gender': 'male', 'color':'blue', 'position':3},
        {'name': 'Mike', 'age': 23, 'gender': 'male', 'color':'blue', 'position':1}]

The goal is to sort the objects in ascending order by position for each color. The expected output should be:

 obj = [{'name': 'Harry', 'age': 16, 'gender': 'male', 'color':'red', 'position':1},
        {'name': 'Sam', 'age': 19, 'gender': 'male', 'color':'red', 'position':2},
        {'name': 'Tom', 'age': 17, 'gender': 'male', 'color':'red', 'position':3},
        {'name': 'Mike', 'age': 23, 'gender': 'male', 'color':'blue', 'position':1}
        {'name': 'Charles', 'age': 19, 'gender': 'male', 'color':'blue', 'position':2},
        {'name': 'Fred', 'age': 21, 'gender': 'male', 'color':'blue', 'position':3}]

Attempted approach:

unique_colors = ['red', 'blue'];
for (var i in unique_colors){
  obj.forEach(function(x){
  if (i === x.colors){
  obj.sort((a,b) => a.position - b.position);
}
}
});

It didn't yield the desired results. Seeking assistance and guidance to rectify the issue. Thank you for your help. I'm still learning Javascript.

Answer №1

To find the index of a specific color and compare it, you can utilize the indexOf function.

let objects = [{'name': 'Tom', 'age': 17, 'gender': 'male', 'color':'red', 'position':3},
        {'name': 'Sam', 'age': 19, 'gender': 'male', 'color':'red', 'position':2},
        {'name': 'Harry', 'age': 16, 'gender': 'male', 'color':'red', 'position':1},
        {'name': 'Charles', 'age': 19, 'gender': 'male', 'color':'blue', 'position':2},
        {'name': 'Fred', 'age': 21, 'gender': 'male', 'color':'blue', 'position':3},
        {'name': 'Mike', 'age': 23, 'gender': 'male', 'color':'blue', 'position':1}];
        
let availableColors = ['red','blue']

objects.sort((a,b) => {
  let indexA = availableColors.indexOf(a.color);
  let indexB = availableColors.indexOf(b.color) ;
  return indexA === indexB ? a.position-b.position : indexA - indexB 
});

console.log(objects);

Answer №2

Here is a custom sorting algorithm:

const obj = [{
    name: "Tom",
    age: 17,
    gender: "male",
    color: "red",
    position: 3
  },
  {
    name: "Sam",
    age: 19,
    gender: "male",
    color: "red",
    position: 2
  },
  {
    name: "Harry",
    age: 16,
    gender: "male",
    color: "red",
    position: 1
  },
  {
    name: "Charles",
    age: 19,
    gender: "male",
    color: "blue",
    position: 2
  },
  {
    name: "Fred",
    age: 21,
    gender: "male",
    color: "blue",
    position: 3
  },
  {
    name: "Mike",
    age: 23,
    gender: "male",
    color: "blue",
    position: 1
  },
];

const result = obj.sort((a, b) => {
  if (a.color === b.color) {
    return a.position - b.position;
  } else return a.color - b.color;
});

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

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

What is the best way to display an image right in the middle of the header?

My project consists of three main files - an HTML, a CSS, and a JS file. I have developed the HTML using the Bootstrap 5.1.3 framework. The issue I am facing pertains to the alignment of the clothing brand logo within the header section. Despite multiple ...

Sending a message in the DELETE route using express.js

I'm having trouble displaying a message after deleting a user. I attempted to use req.session properties and then retrieve them in the GET route, but they seem to not be available. Can anyone suggest a solution for fixing this code? router.get("/", ...

Error message: AngularJS Jasmine spyOn: number has no functionality

I am encountering difficulties while attempting to execute a test that utilizes a mockup for a service call (retrieving location data from a web SQL database). Below is the controller code: .controller('LocationDetailCtrl', function ($scope, $s ...

How to troubleshoot an Ionic exception occurring during the execution of any Ionic command?

Whenever I attempt to run an ionic command, I keep encountering this error message: { Error at FatalException.Exception (C:\Users\crist\AppData\Roaming\npm\node_modules\ionic\node_modules\@ionic\cli-u ...

Issues with React in a Production Environment

After successfully developing a react app and express API that worked correctly in localhost, I decided to move my API to a digitalocean droplet. The droplet only had an IP address and used HTTP. While utilizing the API from the react app in development m ...

When the button is clicked, redirect to a new page and submit a form using AJAX with data obtained from the click event

I have a page called 2.html where inputting an ID number results in some output being displayed. This functionality is achieved using Ajax post method, sending data along with the data parameter. I also have another page named 1.html that contains a list o ...

Tips for creating a countdown timer from scratch without relying on a plugin

Looking at this image, it is clear that jQuery can be used. However, I am wondering if there is a way to create a countdown timer without relying on plugins. Can anyone offer some guidance? ...

JavaScript and jQuery are lightning fast, especially when the page is reloaded

I am currently working on a responsive website that uses liquid layouts. I have encountered challenges when incorporating images in the design, especially when dealing with different browsers like IE, Firefox, and Chrome. Recently, I faced another issue w ...

The Datatable feature is malfunctioning, unable to function properly with Javascript and JQuery

As a novice in the world of jquery/javascript, I find myself struggling with what may seem like an obvious issue. Despite following tutorials closely (the code for the problematic section can be found at jsfiddle.net/wqbd6qeL), I am unable to get it to wor ...

What is the best way to reorganize an object's properties?

Looking for a way to rearrange the properties of an existing object? Here's an example: user = { 'a': 0, 'b': 1, 'c': 3, 'd': 4 } In this case, we want to rearrange it to look like this: user = { &a ...

Show information in a React Native element | Firebase

Just starting out with react native and struggling to display data in a component? You're not alone! I'm having trouble too and would love some guidance on how to destructure the data for display. Any tips? import React,{useState,useEffect} from ...

Encountering a Console warning while working with the Material UI menu. Seeking advice on how to resolve this issue as I am integrating HTML within a text

Caution: PropType validation failed. The prop text provided to LinkMenuItem is invalid as it should be a string, not an object. Please review the render method of Menu. Below is the code snippet: var menuItems = [ // text is not valid text { route: &ap ...

Is there a way to decrease a field in a MongoDB database on a daily basis?

In the process of constructing an Angular2 application using MEAN stack architecture, I have a field called Remaining Days in my MongoDB database. I am interested in having this field automatically decrement by 1 each day. Do you know if this is possible ...

Parsing values from deeply nested objects and arrays

I've come across this issue before, but I'm having difficulty navigating through a nested structure. I can't seem to find any guidance in the right direction. Here is the object I'm attempting to parse: const nestedArray = { id ...

Looking for a way to sort through data using the current time as a filter

In my possession is an object presented below: const user = { id: 3, name: "Clark Kent", mobileNumber: "1234567892", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="385d40595548545d674d4b ...

Traverse a deeply nested JSON structure

I need assistance with looping through a complex JSON object using only JavaScript. My goal is to log each item along with its properties into the console. const nested_json = { "item1":{ "name": "banana", ...

Is there a way for me to iterate through an array of objects within a Redux reducer file in order to remove a specific user?

I am facing a challenge while trying to remove a user in redux. The issue arises when I use the map function in the reducer.js file and encounter a 'state.users.map is not a function' error. Upon investigation, I realized that the array consists ...

Dividing CSV Data into Two File Outputs

I've got a CSV file that's structured like this: Docushare Host locale, created_at, version en,Wed Feb 21 17:25:36 UTC 2018,07.00.00.C1.609 User handle, client_data, docCountQuota User-12,,-2 Document handle,client_data,cfSpecialWords Document ...

Combining AddClass and RemoveClass Functions in Mootools Event Handlers

I am currently in the process of creating a CSS animation, and one aspect involves changing the class name of the body at specific intervals. Since I am relatively new to Mootools (and JavaScript in general), my approach has been to add/remove classes to ...

Experience a login page similar to Google's with a fully functional back button

I'm currently working on a login page that requires the user to enter their username and have it validated before proceeding. Once the username is confirmed as valid, a new input field for password entry should appear. However, I'm facing an issu ...