How can I organize and arrange a JSON object based on specific criteria?

Imagine having a JSON object containing user colors that you want to sort by UserID.

oUserColors = { "users": [
    { "UserID": 31, "Color": "Red" },
    { "UserID": 30, "Color": "Red" },
    { "UserID": 32, "Color": "Green" },
    { "UserID": 30, "Color": "Green" },
    { "UserID": 32, "Color": "Red" }
 ] };

You can achieve this sorting using the following function.

objSortedUserColors = oUserColors.users.sort(function (a, b) {
        return b.UserID - a.UserID; // sorting in descending order based on UserID.
 });

The sorted result will look like this...

 objSortedUserColors = { "users": [
    { "UserID": 32, "Color": "Red" },
    { "UserID": 32, "Color": "Green" },
    { "UserID": 31, "Color": "Red" },
    { "UserID": 30, "Color": "Red" },
    { "UserID": 30, "Color": "Green" }
 ] };

Now, what if you also want to filter out red colors for users who have both red and green? Leaving only green for those users with both colors.

 objFilteredSortedUserColors = { "users": [
    { "UserID": 32, "Color": "Green" },
    { "UserID": 31, "Color": "Red" },
    { "UserID": 30, "Color": "Green" }
 ] };

If you have any ideas or suggestions on how to do this, please share!

Answer №1

Let's talk about filtering the array rather than sorting it since you already know how to do that. One way to filter is by using the reduce function along with a helper object to store values based on UserUD. Another option is to use a Map, but plain objects have the advantage of maintaining order based on increasing keys for non-negative integers.

const oUserColors = { "users": [{ "UserID": 31, "Color": "Red" },{ "UserID": 30, "Color": "Red" },{ "UserID": 32, "Color": "Green" },{ "UserID": 30, "Color": "Green" },{ "UserID": 32, "Color": "Red" }]};

const result = Object.values(oUserColors.users.reduce( (acc, obj) => {
    const prev = acc[obj.UserID];
    if (!prev || prev.Color === 'Red') {
        acc[obj.UserID] = obj;
    }
    return acc;
}, {}));

console.log(result);

The concept here is to create an object (acc) containing only the desired values, organized by UserID. If a value does not exist yet for a specific UserID during this process, it gets added. If there is already a value and its color is Red, then it can be replaced with the current object.

By using Object.values(), you can convert the object back into an Array.

Since JavaScript typically produces values in the order of numerical key order (for non-negative integers), the resulting output will be sorted accordingly.

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

"Enhance your Vue.js application with the powerful capabilities of vue3-easy

I am currently working on a Vue.js project utilizing the "vue3-easy-data-table" library and following the style recommendations outlined on this particular webpage: Despite attempting to apply the following CSS properties: --easy-table-body-even-row-font ...

Can you elaborate on this specific JavaScript concept?

I'm not very knowledgeable about javascript. Could someone please explain this structure to me? [{a:"asdfas"},{a:"ghdfh",i:54},{i:76,j:578}] What exactly is being declared in this structure? It appears to be an array with 3 elements, correct? Each e ...

Refresh the angular form after submitting data

I am currently working on an angular form to input data into a database. My framework of choice is angular-fullstack by yeoman. After successfully submitting the data, I encounter an issue where clearing the form values doesn't allow me to add new en ...

Issue with Saving Modal in Bootstrap 5: Button Does Not Function

I've been following the instructions on , but I'm facing an issue with getting the save button to work on my modal. Initially, I tried placing it within the form tag, but it ended up using the form action from the main view instead of the partial ...

The HTML div captured with html2canvas is incomplete

I am currently developing a meme editor website utilizing the html2canvas library available at Below is the HTML code for the div I aim to capture: <div class="container"> <div id="theUserMeme"> <div class=& ...

Mistake in algorithm for identifying peaks

Hey everyone, I could really use some assistance with my code. My code is for peak finding. In case you're not familiar with the concept of peak finding, here's a quick explanation: Peak finding involves finding a peak element in an array of in ...

I am facing an issue where an AJAX post to Express is not returning any data to req.query. I have tried various solutions but nothing seems to

I have encountered an issue with my setup where the body is empty when sending data through ajax. In Chrome's network tab, I can see the post and content with the correct payload: {"EventName":"asd","PrivacyLevel":1,"TypeInt":1,"ExpectedDate":"asd"," ...

Bringing in a selection of functions as an object using ES6 imports

functions.js export const setA = () => {...} export const setB = () => {...} export const setC = () => {...} component.js import {setA, setB, setC} from 'functions' export class componentOne extends React.Component { constructor(p ...

Having trouble displaying information in JavaScript after using getScript() to retrieve data from an API containing a JSON block database

I'm a newcomer to the world of Ajax/json/jquery and I find myself with a few inquiries. Currently, I am working with an API located at which contains a JSON block that looks something like this [{"id":"1","FirstName":"Micheal","LastName":"Kooling"}, ...

Tips for dynamically adjusting PHP images based on screen size

I am facing issues with page speed due to the images I receive from the server. I am wondering if it's possible to request different image files based on the screen size that the page is being displayed on. I came across this code snippet: if( typeof ...

Building a framework for a bit array in the C programming language

After realizing that there is no built-in structure for a single bit in C, I encountered difficulties while working on a huffman tree. Some character encodings were not an exact 8 bits long, making it inefficient to store them using typical data types like ...

Issue encountered while loading JSON data into DynamoDB's local instance

I have successfully set up DynamoDB local and everything is functioning as expected after going through their documentation. I have also tested their example code, which worked flawlessly. The Users table has been created with the name "Users". Below is ...

Arrows on the button are unresponsive and there seems to be an incorrect number of

I've been working on a project by combining various examples I found online. I'm puzzled as to why it's displaying all the buttons at once instead of just one per page, and why the number of visible buttons decreases by one with each right c ...

What is the best way to make a canvas element fit the entire browser window without causing scroll bars to appear?

My window size isn't working properly, despite attempting the following code: Javascript var game; function game() { this.canvas = document.getElementById('canvas'); this.canvasWidth = window.innerWidth; this.canvasHeight = wi ...

What is the best way to make my navbar reach the edges of the screen?

Currently working on a regular navbar, but aiming to have the logo and links span the entire container instead of starting in the middle. I'm seeking an easy solution that won't push out my links when applied. https://i.sstatic.net/nTFJ6.png ...

Python JSON - Unable to read data due to TypeError: indices in string must be integers

Having trouble reading a JSON file I created in my script. When trying to access one of its "attributes" after reading it, the following error message pops up: Traceback (most recent call last): File "index.py", line 74, in <module> ...

Discovering the window.scrollTop, ScrollY, or any other distance value while utilizing CSS scroll snap can be achieved by following these

I am currently utilizing css scroll snap for smooth scrolling through sections that are 100vh in height. The functionality of the scroll snap is quite impressive. However, I need to find a way to determine the exact distance the user has scrolled down the ...

jQuery dropdown menu button impacts the entire webpage

I created this jQuery code to modify the drop menu elements, but it ended up affecting the entire page. How can I resolve this issue? $(".dropmenuac").on("click",function(){ $(".dropmenulist").css("opacity",& ...

When attempting to call a bundle file using browserify from React, an unexpected character '�' Syntax error is thrown: react_app_testing/src/HashBundle.js: Unexpected character '�' (1:0

Hey there, I'm currently struggling with an unexpected unicode character issue. Let me provide some context: I've created a simple class called HashFunction.js that hashes a string: var crypto = require('crypto') module.exports=class H ...

Can data be retrieved from a redirection page using AJAX?

I'm facing a challenge. I am attempting to complete a task that seems simple, but I am struggling with it. Let me explain the situation: I have 3 different HTML pages: The first page, named index.html, is my main page with a button that triggers a ...