Organize an array of objects based on another array in JavaScript

I have been working on sorting an array of objects by comparing it with another object. The goal is to display the selected objects at the top and the rest below them.

While I am currently achieving the desired output, I am interested in exploring ways to further optimize the process.

let myArray = [
    { Name: 'Name 1', id: 1111 },
    { Name: 'Name 2', id: 2222 },
    { Name: 'Name 3', id: 3333 },
    { Name: 'Name 4', id: 4444 },
    { Name: 'Name 5', id: 5555 },
    { Name: 'Name 6', id: 6666 }]

let selected = { 1111: 'some value 1', 4444: 'some value 2' }

sortBySelected = (data) => {
    var keys = Object.keys(selected);
    return data.filter((obj) => {
        if (keys.find((key) => {
            return key === String(obj.id);
        })) {
            return true;
        }
        return false;
    });
}

sortByNotSelected = (data) => {
    var keys = Object.keys(selected);
    return data.filter((obj) => {
        if (keys.find((key) => {
            return key === String(obj.id);
        })) {
            return false;
        }
        return true;
    });
}

sort = (data) => {
    data1 = sortBySelected(data);
    data2 = sortByNotSelected(data);
    return data1.concat(data2);
}


console.log(sort(myArray));

Answer №1

To check for the presence of an element in an array, you can utilize the delta of the check with the in operator.

var myArray = [{ Title: 'Title 1', key: 1234 }, { Title: 'Title 2', key: 5678 }, { Title: 'Title 3', key: 9876 }],
    chosen = { 1234: 'value 1', 5678: 'value 2' };
    
myArray.sort((x, y) => (y.key in chosen) - (x.key in chosen));

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

Answer №2

To organize your array, utilize the Array.sort method.

myArray.sort(function(a, b) {
  var aChosen = selected[a.id] !== undefined;
  var bChosen = selected[b.id] !== undefined;
  if (aChosen && !bChosen) {
    // place a before b
    return -1;
  } else if (!aChosen && bChosen) {
    // place a after b
    return 1;
  } else {
    // a and b have equal priority...
    // let the sorting function determine their exact order
    return 0;
  }
});

Answer №3

When both sortBySelected and sortByNotSelected are called, the JavaScript loop iterates twice over the array. While using Array.sort may seem more elegant, it does not appear to be less costly.

I conducted some testing with a small StackBlitz example: https://stackblitz.com/edit/stackoverflow-68784575

The sort function was the initial suggestion, sort2 loops only once instead of twice, and sort3 uses Array.sort.

The results showed that sort2 appears to be more efficient. You can view the result image here:

see result image here

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

If you want to retrieve the calculated value of a div using jQuery

I have a scenario where I have 3 list items (li) under an unordered list (ul). I am interested in finding the height of these list items, but without explicitly defining their height. So far, when inspecting with Firebug, I noticed that the computed height ...

Ways to verify whether a callback function supplied as a parameter in Javascript has any arguments

My task involves implementing the following: doSomething .then(success) .catch(failure); The success and failure functions are callbacks that will receive their value at runtime (I am developing a module). Therefore, I need to ensure that the fa ...

Is it possible to remove the for loop from this particular PHP script?

Is it feasible to determine the smallest missing number in a range of whole numbers without utilizing a loop structure? In cases when there are no missing numbers, should the function return the maximum value from the range plus one? This is how I approac ...

What is the best method to add data to a child array located within a nested array?

Struggling to create an array that will display data in the following format: Healthcare -- Insights driven by data for improved healthcare -- Urban Analytics Transport -- Urban Analytics Cities -- Urban Analytics I have attempted ...

What could be the underlying reason for the unusual behavior observed in this range polyfill implementation?

I am attempting to transform an HTML5 range input into a set of radio buttons. Each radio button corresponds to a value within the original range, with text displaying its value. However, I am encountering an issue where the last piece of text, meant to sh ...

An error in the floating point has occurred while attempting to generate prime numbers

My program is capable of generating prime numbers. The code functions as expected when I request the first 100 or 200 primes, but encounters a Floating Point Exception error when I attempt to generate prime numbers beyond 300. It appears that the issue l ...

Is there a way to determine if a parent of my HTML element possesses a CSS class?

Looking at this HTML code snippet - <div id="parent" class="foo"> <div id="child"> </div> </div> Is there a way to create a test to verify if the child element is utilizing the foo class? I attempted: element .children("#chi ...

When dynamically adding input fields in Bootstrap, there is a smaller gap between inline inputs

When adding a new list item dynamically in a modal using jQuery append, the spacing in the first li element seems to have a larger gap between the input fields compared to the rest that are added later. Even after checking the developer tools and confirmin ...

encase a function with javascript

let myString = "I am creating a program."; //function to calculate number of letters const letterCount = (str) => str.length; //function to calculate number of words const wordCount = (str) => str.split(" ").length; //function ...

Tips for verifying the status of an input element following the dynamic addition of a required element

I have implemented a required field for all input elements in a specific state using the following code: for (var i = 0; i < data.length; i++) { // activate required function v = data[i].Required; if (v) document.ge ...

Issue: Module - webpack-dev-server.js cannot be located

I'm in the process of creating a React app from scratch. Typically, I use npm create-react-app which sets everything up for you automatically. Following this tutorial https://www.youtube.com/watch?v=deyxI-6C2u4&ab_channel=TraversyMedia has been he ...

What is the method for entering a value in Code Mirror using Selenium WebDriver?

Struggling with inserting input values into Code Mirror, which is HTML code. Any assistance would be greatly appreciated! This is what I have been attempting so far (but I need to insert values on each line of Code Mirror) JavascriptExecutor js = (Javas ...

Guidelines on resolving the issue of Unsupported platform for [email protected]: requested {"os":"darwin","arch":"any"} (existing: {"os":"win32","arch":"x64"})

Trying to install Parallelshell but encountering a persistent warning. I've checked the package file multiple times without finding a solution. Can someone assist me with this issue? ...

Limit the precision of decimal number output to a specific value

I need assistance with achieving the output 999999.35 in angular or javascript combined with html. I am looking to restrict the number of 9's to a maximum of 6 digits before the decimal point, and after 6 digits it should not accept any more digits. A ...

What advantages does the use of $(e).attr(name,value) offer compared to using e.setAttribute(name,value)?

Scenario: The variable "e" represents an element of type "HtmlElement" and not a "css selector" I am referring to any attribute, not just the standard allowed ones like "atom-type" or "data-atom-type". Regardless of the attribute name, will it function wi ...

Emails not being sent by Nodemailer

I recently configured my glitch project with a contact form and I'm attempting to set it up so that it sends me an email when someone fills out the form. The issue I'm experiencing is that while the server console logs indicate that the message h ...

Ways to compare arrays and display the elements that are missing from the array

I have two arrays with different values and I want to compare them to separate the values that do not match. This is my current script: var array_must_exist = ['4','5']; var array_to_compare = [{"NO": "1"},{"NO": "2"},{"NO": "5"},{"NO" ...

How to insert an HTML element in between multiple list items using jQuery

I have a variety of div elements that I want to group together using jQuery's append method: Here are the initial div elements: <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div& ...

Node.js socket.io: How to Handle Multiple Returned Values from a Single Event

I've been working on a simple chat app using Node, Express (^4.15.3), and socket.io (^2.0.3). However, every time I add a new message, I notice that I get an additional response each time. For instance, when I send the message "Hello" for the first t ...

What is the best way to distribute components between two NextJS projects?

Confused about the best way to share ReactJs components between two NextJs applications - one for e-commerce and the other for a manager portal. In the e-commerce app, there are various UI components that I want to reuse in the manager portal. Considering ...