Sorting and grouping data in JavaScript through the use of sorting methods

I need to rearrange the elements in an array to form groups. The first element should be one with a uniqueID and empty parentDocId, followed by elements with parentDocId matching the uniqueID of the first element. Elements with an empty parentDocId and no parent uniqueID should be placed at the bottom of the array.

Here's an example of my expected output:

[
    {
      name: 9,
      uniqueID: '22222',
      parentDocId: '',
    },
    {
      name: 11,
      uniqueID: '3463452345',
      parentDocId: '22222',
    },
    {
      name: 15,
      uniqueID: '3333',
      parentDocId: '',
    },
    {
      name: 19,
      uniqueID: '234235346',
      parentDocId: '3333',
    },
    {
      name: 346345,
      uniqueID: '11111',
      parentDocId: '',
    },
    {
      name: 7,
      uniqueID: '456456456',
      parentDocId: '11111',
    },
    {
      name: 55,
      uniqueID: '346345345',
      parentDocId: '',
    },
    {
      name: 77,
      uniqueID: '568567568567',
      parentDocId: '',
    },
  ];

And here's what I currently get:

[
    {
        "name": 55,
        "uniqueID": "346345345",
        "parentDocId": ""
    },
    {
        "name": 77,
        "uniqueID": "568567568567",
        "parentDocId": ""
    },
    {
        "name": 7,
        "uniqueID": "456456456",
        "parentDocId": "11111"
    },
    {
        "name": 346345,
        "uniqueID": "11111",
        "parentDocId": ""
    },
    {
        "name": 19,
        "uniqueID": "234235346",
        "parentDocId": "3333"
    },
    {
        "name": 15,
        "uniqueID": "3333",
        "parentDocId": ""
    },
    {
        "name": 11,
        "uniqueID": "3463452345",
        "parentDocId": "22222"
    },
    {
        "name": 9,
        "uniqueID": "22222",
        "parentDocId": ""
    }
]

This is the code that I am using:

items.sort((a, b) => {
    if (a.parentDocId === b.uniqueID) {
      return -1;
    } else if (b.parentDocId === a.uniqueID) {
      return 1;
    } else if (a.parentDocId === '' && b.parentDocId !== '') {
      return -1;
    } else if (a.parentDocId !== '' && b.parentDocId === '') {
      return 1;
    } else {
      return 0;
    }
});

Answer №1

After carefully analyzing the issue, I have come up with a potential solution.

let items = [
    {
        "name": 55,
        "uniqueID": "346345345",
        "parentDocId": ""
    },
    {
        "name": 77,
        "uniqueID": "568567568567",
        "parentDocId": ""
    },
    {
        "name": 7,
        "uniqueID": "456456456",
        "parentDocId": "11111"
    },
    {
        "name": 346345,
        "uniqueID": "11111",
        "parentDocId": ""
    },
    {
        "name": 19,
        "uniqueID": "234235346",
        "parentDocId": "3333"
    },
    {
        "name": 15,
        "uniqueID": "3333",
        "parentDocId": ""
    },
    {
        "name": 11,
        "uniqueID": "3463452345",
        "parentDocId": "22222"
    },
    {
        "name": 9,
        "uniqueID": "22222",
        "parentDocId": ""
    }
]

let sortedArrays = [];

items.forEach(object=>{
   if(!object.parentDocId){
     sortedArrays.push([object]);
    
    }

})

sortedArrays.forEach(arg=>{

  items.forEach(object=>{
    if(arg.slice(-1)[0].uniqueID==object.parentDocId){
     
      arg.push(object)
     }
  })
})
let flatArray = sortedArrays.flat(1)
console.log(flatArray)

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

Switching between javascript objects within the redux store and the application

I am working with a set of JavaScript objects that are retrieved from an external API library. My goal is to save these objects in my React application using Redux. These objects are ES2015 classes that include two useful methods called fromJSON and toJSO ...

I want to create a clickable image using Vue.js

Whenever I click on the image, I aim to apply a particular class to it. Here is how I am currently trying to accomplish this: <div class="thumbnail"> <img :image_id="image.id" :src="'/storage/images/'+image.name" ...

What is the best approach for managing this type of printing in Java?

When printing the string "The winner is student 1 student 2 student 4 student 5 with points 20", I want the output to be "The winner is student 5 with points 20." If more than one student has the same score, the desired output should be "The winner is stu ...

TypeScript Redux actions not returning expected type

Basically, I am attempting to assign types to a group of functions and then match them in my Redux reducer. Here are the functions I have defined in actions.ts: export const SET_CART_ITEMS = "SET_CART_ITEMS"; export const SET_CART_TOTALS = "SET_CART_TOTA ...

I encountered an issue while trying to integrate VideoJS with React

While using VideoJS, the video plays without any issues. However, I am facing an issue where the available source options are not being displayed as they should be. I attempted to use a plugin for the sources, but even then, the options didn't show u ...

Utilizing JavaScript for selecting a radio button on click event

I have implemented a feature with four radio buttons to select a country. Upon clicking on any of the radio buttons, I utilize Ajax to retrieve the states corresponding to that specific country. To indicate to the end user that data processing is ongoing, ...

Using Browserify to load the npm-module client-side for thepiratebay

I am currently facing an issue with my node.js server file. It successfully loads my site and runs JavaScript, but I encountered a problem when trying to include tpb = require('thepiratebay'); in the server.js file. Although it works fine in the ...

A Step-by-Step Guide to Retrieving the Route of a Controller Function in Express

When working with Express.js, it is possible to retrieve the names of all controllers from an app. However, these names are usually in an unfamiliar format (such as handle: [AsyncFunction: login]). I have been unable to figure out how to destructure this i ...

JavaScript popup confirmation in an MVC3 AJAX form

I have implemented an ajax form in a MVC3 project and I am looking for a way to incorporate a JavaScript confirm popup upon clicking the submit button. While I have managed to get the popup to display, I am struggling to prevent the form submission if the ...

Angular material textarea with autocomplete functionality

Is there an Angular (2 and above) textarea autocomplete component available? I've tried out the following components: https://github.com/jeff-collins/ment.io https://github.com/jdcrensh/angular-otobox However, these are built using jQuery and An ...

What does the single-threaded nature of JavaScript signify in terms of its intricacies and ramifications?

As someone relatively new to Javascript and JQuery, I recently discovered that Javascript operates on a single-threaded model. This has left me wondering about the implications it carries: What should be taken into account when writing JavaScript code? Ar ...

How to find and handle duplicated elements within an array using Ruby

I am working with an array called rangers, which consists of colors like "red", "blue", "yellow", "pink", and "black". I have intentionally left out green from the list. My goal is to double each element in the array so that it looks like this: rangers = ...

When employing TypeScript, an error pops up stating "cannot find name 'ObjectConstructor'" when attempting to use Object.assign

I am rephrasing my query as I realized it was unclear earlier. I have an API that is sending me data in the following format: {"photos":[{"id":1,"title":"photo_1_title"}]} In my code, I have a variable called photos and a function named getPhotos() For ...

Setting Default Value in Dropdown List with Angular Reactive Forms

Having trouble setting the default option in a select element. I receive an array from the server and want to automatically select the second item in the array (documentTypes[1]). Below is my code snippet along with what I have attempted so far. Select HT ...

Utilizing Vue's computed function to filter values from a JSON dataset

How do I efficiently filter an array of JSON data? Here is the code snippet: <div v-if="vacciCounter"> <b-card no-body class="mb-2" v-for="(stateObject, state) in filteredList" v-bind:key="state"& ...

Comparing tick and flushMicrotasks in Angular fakeAsync testing block

From what I gathered by reading the Angular testing documentation, using the tick() function flushes both macro tasks and micro-task queues within the fakeAsync block. This leads me to believe that calling tick() is equivalent to making additional calls pl ...

Smooth Transitions When Adding and Removing Components

Essentially, I am looking to achieve something similar to this: visible ? <Fade> <SomeComponent/> </Fade> : undefined My goal is to smoothly transition individual elements without having to control the state of the Fade component fr ...

Transform a group of strings into ObjectId using Mongo, then proceed to delete them

I am currently working with an array of strings containing ids. My goal is to convert these strings into ObjectIds and then use them to delete records from the collection. arrOfStr = ['6346ed8f0c2437c710321c4e','6346ed8f0c2437c710321c4f&apos ...

Troubles encountered when populating the array within a Vue component

I am experiencing an issue with my ProductCard component where the addItem method is not successfully adding a new item to the array. <template> <div class="card"> <div v-for="item in TodoItems" :key="item.id ...

What is the best way to run through each item in an array and then promptly provide a response to the client

I am a beginner in async programming and despite seeing this question asked multiple times, I still struggle to understand and solve the issue. My current project involves using nodeJs and the MsSql module to connect to a SQL Server. In my nodejs app, I h ...