How to arrange an array of objects by a property within a nested object using JavaScript?

var originalArray = [
    {
        name: 'Shop1',
        stock: [
            { name: 'Apples', quantity: [{ id: "something", time: 11 }, { id: "something", time: 44 }, { id: "something", time: 53 }] },
            { name: 'Bananas', quantity: [{ id: "something", time: 3 }, { id: "something", time: 91 }, { id: "something", time: 3 }] },
            { name: 'Grapes', quantity: [{ id: "something", time: 2 }, { id: "something", time: 91 }, { id: "something", time: 3 }] },
            { name: 'Pineapple', quantity: [{ id: "something", time: 8 }, { id: "something", time: 91 }, { id: "something", time: 3 }] }
        ]
    },
    {
        name: 'Shop2',
        stock: [
            { name: 'Laptop', quantity: [{ id: "something", time: 31 }, { id: "something", time: 11 }, { id: "something", time: 23 }] },
            { name: 'Phone', quantity: [{ id: "something", time: 1 }, { id: "something", time: 11 }, { id: "something", time: 23 }] },
            { name: 'Tablet', quantity: [{ id: "something", time: 111 }, { id: "something", time: 11 }, { id: "something", time: 323 }] }
        ]
    }
];

For instance, in the provided array, stock and quantity are nested keys with an array of objects as their value.
Shop2 has

{ id: "something", time: 323 }
which has a higher time than any item in Shop1
After sorting, Shop2 will be first in the list and Shop1 will be in second position, and so on, time descending

My code is not correctly sorting the shops.
It should not sort the nested array in stock & quantity, just sort the Shop order by time descending

const sorted = originalArray
  .map(shop => shop.stock
  .map(stk => stk.quantity
  .map(item => Object.entries(item)[1])))
  .sort((a, b) => b[1].time - a[1].time)
  .map(item => item[1])

console.log(JSON.stringify(sorted));

EXPECTED OUTPUT

// sorted array
[
    {
        name: 'Shop2',
        stock: [
            { name: 'Laptop', quantity: [{ id: "something", time: 31 }, { id: "something", time: 11 }, { id: "something", time: 23 }] },
            { name: 'Phone', quantity: [{ id: "something", time: 1 }, { id: "something", time: 11 }, { id: "something", time: 23 }] },
            { name: 'Tablet', quantity: [{ id: "something", time: 111 }, { id: "something", time: 11 }, { id: "something", time: 323 }] }
        ]
    },
    {
        name: 'Shop1',
        stock: [
            { name: 'Apples', quantity: [{ id: "something", time: 11 }, { id: "something", time: 44 }, { id: "something", time: 53 }] },
            { name: 'Bananas', quantity: [{ id: "something", time: 3 }, { id: "something", time: 91 }, { id: "something", time: 3 }] },
            { name: 'Grapes', quantity: [{ id: "something", time: 2 }, { id: "something", time: 91 }, { id: "something", time: 3 }] },
            { name: 'Pineapple', quantity: [{ id: "something", time: 8 }, { id: "something", time: 91 }, { id: "something", time: 3 }] }
        ]
    }
]

Answer №1

Here is a solution that should do the trick:

function findHighestTime(inventory) {
  let maximum = 0;
  for (const item of inventory) {
    for (const obj of item.quantity) {
      if (obj.time > maximum) maximum = obj.time;
    }
  }
  return maximum;
};

const sortedInventory = originalInventory.sort((a, b) => findHighestTime(b.inventory) - findHighestTime(a.inventory));

Answer №2

This method may not be the most optimized, but it gets the job done

var originalArray = [
    {
        name: 'Shop1',
        stock: [
            { name: 'Apples', qt: [{ id: "something", time: 11 }, { id: "something", time: 44 }, { id: "something", time: 53 }] },
            { name: 'Banana', qt: [{ id: "something", time: 3 }, { id: "something", time: 91 }, { id: "something", time: 3 }] },
            { name: 'Grapes', qt: [{ id: "something", time: 2 }, { id: "something", time: 91 }, { id: "something", time: 3 }] },
            { name: 'Pineapple', qt: [{ id: "something", time: 8 }, { id: "something", time: 91 }, { id: "something", time: 3 }] }
        ]
    },
    {
        name: 'Shop2',
        stock: [
            { name: 'Ramen', qt: [{ id: "something", time: 31 }, { id: "something", time: 11 }, { id: "something", time: 23 }] },
            { name: 'Sushi', qt: [{ id: "something", time: 1 }, { id: "something", time: 11 }, { id: "something", time: 23 }] },
            { name: 'Tempura', qt: [{ id: "something", time: 111 }, { id: "something", time: 11 }, { id: "something", time: 323 }] }
        ]
    }
];
const sorted = originalArray.slice().sort((a, b) => {
    maxA = Math.max(...a.stock.flatMap(({qt})=>qt.map(({time})=>time)));
    maxB = Math.max(...b.stock.flatMap(({qt})=>qt.map(({time})=>time)));
    return maxB-maxA
});
console.log(sorted);

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

Surprising "unexpected end of line" JavaScript lint notification out of nowhere

In this simplified version of my JavaScript code: function addContent() { var content = []; content.append( makeVal({ value : 1 }) ); // lint message generated } After running a lint program, I received the followi ...

Is there a more efficient method for performing multiple JavaScript replace calls rather than executing them individually?

In my Javascript code, I am creating a string that includes HTML content. Currently, my approach involves the following steps: var filter = ""; filter = util.getTemplate( "tmp_filter", temps ); filter = filter.replace( 'id="tmp_filter"','& ...

Unexpectedly, the CommandInteraction feature came to a halt within Discord.js slashcommands

I was having no issues with this code, but now it's throwing an error: const {Client, CommandInteraction, MessageEmbed, Permissions} = require("discord.js"); module.exports = { name : 'ban', description : "bans the tar ...

How to Handle Jquery POST Data in Express Servers

Update Make sure to check out the approved solution provided below. I ended up fixing the issue by removing the line contentType: 'appliction/json', from my POST request. I'm facing a problem trying to send a string to Node.js/Express becau ...

What steps can I take to minify my code using react-create-app?

Currently, I am facing an issue with minifying my code on the server. Despite running npm run build, which is supposed to handle all the minifying processes (as shown here: https://i.stack.imgur.com/wjpd7.png), I still see the unminified code when accessin ...

Incorporating invisible surprises into a fixed menu that reveal themselves as you scroll

I am working on implementing a top navigation and a sticky sub-navigation feature. The goal is to have the sticky nav become the top nav when the user scrolls down the page, similar to the functionality on this website - The issue I'm facing is with ...

Encountered a TypeScript error: Attempted to access property 'REPOSITORY' of an undefined variable

As I delve into TypeScript, a realm unfamiliar yet not entirely foreign due to my background in OO Design, confusion descends upon me like a veil. Within the confines of file application.ts, a code structure unfolds: class APPLICATION { constructor( ...

Leveraging Discord.JS to seamlessly transport users in Discord to their designated voice channel by assigning roles

I'm attempting to transfer all users with a specific role from a voice channel using a command like: !summon @role This command should bring only the users with that specific role to the voice channel where the command was entered My current code is ...

Is it true that eliminating white spaces can enhance a website's loading speed?

I'm curious about something. Can removing white space actually make a website load faster? For instance, take a look at the following CSS snippet - body{ overflow-wrap:break-word; word-break:break-word; word-wrap:break-word } .hidden{ display:none } . ...

What is the best way to iterate through an array of objects in React and JavaScript, adding a new property to each object in order to generate a new array

Greetings, I am currently dealing with an array of objects structured as follows: const arr_obj = [ { children: [{}], type: "type1", updated: "somevalue", }, { children: [{}], type: ...

Is there a way to execute a JavaScript function within a loop?

I need to repeatedly call a JavaScript function multiple times. I have attempted to do so in the following way: In Script function changeIt(strgr , idx) { //SomeCode return; } In C# protected void btn_Click(object sender, EventArg ...

Transform JSON String into Object using jQuery

Recently, I came across a JSON String in this format. {"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11‌​464"} I needed to convert it into an object structure like this [{"label":"label","label1":"67041","label2":"745"," ...

Accessing objects within an array of arrays of objects in react – a guide

First, I executed the following function: const getData = async (array,s,number) => { const response = await axios.get(s); const theData = response.data array[number]=theData } Then, I did this: let array=[] ...

I'm struggling to change the color of a plane geometry in three.js, it always ends up black. Can anyone help me with this issue?

I'm currently working on adding a plane to the scene, and here's how I'm doing it: var plane = new THREE.Mesh(new THREE.PlaneBufferGeometry(300, 300), new THREE.MeshPhongMaterial({specular: '#fff',fog: false,color: '#ff9a0 ...

Perform an ajax POST call to a server using ajax/jQuery techniques

I am attempting to utilize ajax to send a post request to a different domain and receive a json response. The server is located within my company premises and the logs show that it is indeed sending back a json response. Below are two samples of my attemp ...

Each time I use console.log to display a user's radio button choice, the output is consistently lagging by one step

It seems that I am experiencing an issue where the console.log output for a user's radio button selection is always one step behind. This occurs even though I have initially set the default radio button selection to "all". For example, when a user cli ...

Tips for implementing orderBy and filter in ng-repeat when working with an object instead of an array

I am facing a data structure that looks like this: $scope.people = { "ID123": { name_de: "Andre", name_en: "Anrew", age: 30, description: "He is the father of xyz and . . .", . . . ...

The feature of using a custom find command in Cypress does not support chaining

I am interested in developing a customized Cypress find command that can make use of a data-test attribute. cypress/support/index.ts declare global { namespace Cypress { interface Chainable { /** * Creating a custom command to locate a ...

Experience the enhanced features and optimized performance of Onsen 2.0 compared to the earlier version

Apologies if this question is too simplistic, but I am finding some conflicting information in the documentation about using Onsen with Monaca. I am currently utilizing Monaca cloud and I prefer to work solely with pure JS, without incorporating Angular ...

Implementing a button callback function using Aurelia binding

Is there a way to pass an array of custom button objects to a specific element? Here's an example: <my-component header="My Title" buttons.bind="[{icon: 'fa-plus', display: 'New', action: onNew}]"> </my-component> ...