organize an array or JSON based on a numeric value or object in JavaScript

I encountered an issue related to sorting in JSON data. I have a list that can be reordered and the new order needs to be saved so that when the user returns, they see the list in the same customized order. Please refer to the image below: https://i.sstatic.net/6okK3.png The ordering information gets saved in an object and upon retrieval, the JSON appears as shown in this example: https://i.sstatic.net/BaiPT.png. The object ResourceSortedOrder specifies the order in which items should appear, with checked items having a numerical position while others remain null. Based on this ordering, I am attempting to sort the array/JSON using the following JavaScript code:

for (var i = 0; i < lst.length; i++) {
                  if (lst[i].ResourceSortedOrder != null) {
                   var temp = lst[i];
                  lst.splice(i, 1);
                  lst.splice(temp.ResourceSortedOrder, 0, temp);
                  lst.join();
                }


            }

Although it sorts the data, there is a problem where the first element intended for the 5th position ends up at the 4th position due to the presence of '100srvc resources' above it in the JSON. This leads to inaccurate results as depicted in the following image: https://i.sstatic.net/8Mhza.png How can I achieve the desired outcome instead of what is currently displayed?

Here is the JSON data in string format:

"[{"__type":"BusinessLayer.DTOApptResource","ResourceInClinicID":null,"ResourceInClinicName":null,"ResourceID":"d322a490-60ba-4739-a4ce-7d1de52f1789","ResourceName":"Dr. Maity","ResourceType":"Staff","ResourceRoster":[],"ResourceNotAvailableFrom":"0001-01-01T00:00:00.000Z","ResourceNotAvailableTo":"0001-01-01T00:00:00.000Z","ResourceSortedOrder":5,"ResourceKey":"Staff:d322a490-60ba-4739-a4ce-7d1de52f1789"},{"__type":"BusinessLayer.DTOApptResource","ResourceInClinicID":null,"ResourceInClinicName":null,"ResourceID":"e7217073-0763-4c42-8da0-7b4ce81f886a","ResourceName":"Dr. Shome","ResourceType":"Staff","ResourceRoster":[],"ResourceNotAvailableFrom":"0001-01-01T00:00:00.000Z","ResourceNotAvailableTo":"0001-01-01T00:00:00.000Z","ResourceSortedOrder":1,"ResourceKey":"Staff:e7217073-0763-4c42-8da0-7b4ce81f886a"},{"__type":"BusinessLayer.DTOApptResource","ResourceInClinicID":null,"ResourceInClinicName":null,"ResourceID":"670a9ec7-7502-4710-91d3-1c0dbe3023be","ResourceName":"TEST NEW DSHOME","ResourceType":"Staff","ResourceRoster":[],"ResourceNotAvailableFrom":"0001-01-01T00:00:00.000Z","ResourceNotAvailableTo":"0001-01-01T00:00:00.000Z","ResourceSortedOrder":2,"ResourceKey":"Staff:670a9ec7-7502-4710-91d3-1c0dbe3023be"},{"__type":"BusinessLayer.DTOApptResource","ResourceInClinicID":null,"ResourceInClinicName":null,"ResourceID":null,"ResourceName":null,"ResourceType":null,"ResourceRoster":null,"ResourceNotAvailableFrom":"0001-01-01T00:00:00.000Z","ResourceNotAvailableTo":"0001-01-01T00:00:00.000Z","ResourceSortedOrder":null,"ResourceKey":":"},{"__type":"BusinessLayer.DTOApptResource","ResourceInClinicID":null,"ResourceInClinicName":null,"ResourceID":"","ResourceName":"Hair care","ResourceType":"NonStaff","ResourceRoster":null,"ResourceNotAvailableFrom":"0001-01-01T00:00:00.000Z","ResourceNotAvailableTo":"0001-01-01T00:00:00.000Z","ResourceSortedOrder":null,"ResourceKey":"NonStaff:Hair care"}, ...

Answer №1

outcome represents the outcome.
The organize method is not utilized.

var selectedItems = [];
var unselectedItems = [];

list.forEach(function(element){
    if(element.ResourceSortedOrder !== null){
        selectedItems.push(element);
    }else{
        unselectedItems.push(element);
    }
});

var resultArray = [];

selectedItems.forEach(function(element){
    resultArray[element.ResourceSortedOrder] = element;
});

var currentIndex = 0;

unselectedItems.forEach(function(element){   
    while(resultArray[currentIndex]){
        currentIndex ++;
    }
    resultArray[currentIndex] = element;   
});

Answer №2

Try using the code snippet below instead of a traditional for loop to sort the "lst" array.

 lst.sort(function (a, b) {
    var a1 = a.ResourceSortedOrder, b1 = b.ResourceSortedOrder;
    a1 = a1 == null ? 99999 : a1;
    b1 = b1 == null ? 99999 : b1;

    return a1 - b1 ;
});

Answer №3

This snippet of code is designed to arrange items in a list based on the designated "ResourceSortedOrder".

var sortedList = [];
for (var i = 0; i < lst.length; i++) {
    var count = lst.length - sortedList.length;
    var item = null;
    for (var j = 0; j < count; j++) {
        if (lst[j].ResourceSortedOrder == i) {
            item = lst[j];
            break;
        }
    }
    if (item != null) {
        sortedList.push(item);
    }
    else {
        sortedList.push(lst[i]);
    }
}
lst = sortedList;

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

having difficulty grasping the variable's scope within this code

Here we have a code snippet where the variable vid is initialized inside a function. The question arises on how this variable can be used outside the function, specifically in the context of vid.play(). How does the program know that vid was created usin ...

Processing JSON Serialization from Controller to AJAX Response

I'm struggling to find the correct way to use an HttpWebRequest, and then convert its response into a readable format of JSON for a JavaScript AJAX function. If I just return the raw text, it includes escaping slashes in the response. If I deserializ ...

Embedded Javascript fails to function following an async postback triggered by an UpdatePanel

After embedding some JavaScript files in a server control, everything works fine. However, when the server control is placed within an ajax UpdatePanel, it ceases to function after an async postback triggered within the updatepanel. This is the code in th ...

Vue3 - Implementing a seamless communication channel between two child components

Vue 3 has brought about changes in my component structure, as shown below: https://i.sstatic.net/bgtPB.png In this setup, ChildA can communicate with ChildB and requires ChildB to update its state accordingly. In Vue 2, I could send an event from ChildA: ...

Exploring X3DOM nodes using d3.js

I'm attempting to loop through X3DOM nodes in D3.js, but I'm encountering an issue. Check out the code snippet below: var disktransform = scene.selectAll('.disktransform'); var shape = disktransform .datum(slices ...

What advantages does Protractor offer for non-angular applications?

I am in the process of setting up automated tests and am curious about the advantages of using Protractor to automate non-angular applications. Can anyone shed some light on the benefits compared to solely using webdriverJS? ...

Why does my function only execute once? I am attempting to run the function multiple times, but it seems to only run once before the previous invocation is completed

Currently, I'm in the process of working on a book that utilizes a page turn effect in jQuery without the use of any plugins. The implementation of the page turn effect works smoothly when navigating through pages one by one. However, my goal now is t ...

Exploring methods for testing an HTML page that utilizes jQuery for DOM manipulations

Recently, I was tasked with creating an HTML page that utilized jQuery DOM manipulations. For instance, upon clicking the submit button, a success or error message should be displayed. Testing these functionalities is something I'm familiar with in An ...

How to Use $scope within a Function in AngularJS

When a page is loaded, I run the following function: $scope.showTags = function(Id) { $scope.toggleSelectedBlocks = function selectB(block) { // There is a checkbox to be selected... } $scope.greetUser() { console.log("GREETIN ...

The server is currently unable to process my JSON object

I'm encountering an issue with my AJAX program not accepting the JSON object that I am trying to pass. I have an MDF file accessed by registerdb which I believe is accurate. It contains 3 columns: ids, username, and password filled with data. Any as ...

Issue with NextAuth v4 Credentials Provider failing to provide an Id when requested

After successfully implementing next-auth for login, I encountered an issue where the user id from the database was not showing up in the session. Only the values that I provided as null were displaying. import NextAuth from 'next-auth' import Cr ...

What is the best way to find the elements in one array that are not present in another array?

When working in Ruby, performing operations like the following is quite straightforward: fruit = ['banana','apple','tangerine','orange','lemon','lime','kiwi','mango','gua ...

There was an issue with the Discord.js (v12) Giveaway Command that resulted in an error stating "Error: Cannot read property 'hasPermission' of undefined"

Hey everyone, I'm trying to develop my own Discord bot and I want to add a giveaway command to it. I found an example code online that I tried to implement, but unfortunately, it's not working as expected... const ms = require('ms'); c ...

Finding the smallest value within a collection of JSON objects in an array

Looking at the following list, I am in search of the lowest CPU value: [{'Device': 'A', 'CPU': 10.7, 'RAM': 32.5}, {'Device': 'B', 'CPU': 4.2, 'RAM': 32.4}, {'Device' ...

Updating a property of a JavaScript class using a callback function inside the class method after an AJAX request

Here is the code snippet from my JavaScript file: var myApp = myApp || {}; myApp.TestClass = function () { this.testProperty = null; } myApp.TestClass.prototype = { constructor: this, testMethod: function () { var testClass = this; ...

Attempting to implement real-time AJAX search feature in the sidebar

I am fairly new to AJAX searching and still getting the hang of Rails. My goal is to add a search form to the sidebar of my app that appears on every page, with search results displaying on the current page only when a search query is entered. Currently, ...

I'm curious as to why IPC messages from one menu item in Electron can successfully reach my window, but when sent from a different menu item, they do not seem to

I am working on a straightforward application that requires running a background process to fetch some data. I want to display a loading indicator while the data is being retrieved, but I am encountering difficulties implementing this feature. My approach ...

Enabling the submit button only when text is entered in the text fields using jQuery

I have a script that automatically submits a form when two textfields are filled using variables from local storage. The script checks if the variables for email and password are not null before submitting. if (localEmail != null && localPwd != null) { ...

Searching with regex to find keys in an object structured like JSON

Here is a similar object in JSON-like format: { id: "123", name: "John Doe", age: 30, city: "Seattle", email: "johndoe@example.com", phone: "123-456-7890", address: "123 Main St", zipcode: "98101", country: "USA" } I am looking to identify all the keys i ...

Dynamic Components in Vue.js Router

In my quest to develop a single-page vue.js application using vue-router, I have set the default route (/) as a list of links to other pages resembling a landing page. Currently, all other pages function as dialogs for various scenarios. To simplify creati ...