What is the best way to divide an array of objects into three separate parts using JavaScript?

I am looking to arrange an array of objects in a specific order:

The first set should include objects where the favorites array contains only one item. The second set should display objects where the favorites array is either undefined or empty. The third set should consist of objects with more than one item in the favorites array.

Here is how the array of objects is structured:

[
{
rentalName:
rentalAddress:
favorites:[]
...
}
]

I came across a similar solution but it does not cater to the sorting requirement mentioned above:

function sortBy(selector) {
  const cmp = (a, b) => (selector(a) - selector(b));
  return list => list.sort(cmp);
}

const data = [{ rentalName: "Foo", favorites:[{}, {}, {}] }, { rentalName: "Bar", favorites:[{}] }, { rentalName: "Baz", favoriteslikes:[{}] }, { Name: "Plugh", favorites:[] }];

const sortByLikes = sortBy(({ favorites }) => favorites.length);

console.log(sortByLikes(data));

Is there a way to sort the array of objects into three parts as described earlier?

Answer №1

This code snippet is not about sorting elements, instead it focuses on categorizing them into different groups.

To achieve this, a forEach loop is used to iterate through an array of objects and place each object into a specific array based on a certain condition.

function groupByFavorites(array) {
    let result = {
        none: [],
        one: [],
        multiple: []
    };
    array.forEach(o => {
        if (!o.favorites) { // If favorites property is undefined or empty
            result.none.push(o);
        } else if (o.favorites.length == 1) {
            result.one.push(o);
        } else {
            result.multiple.push(o);
        }
        return result;
    });
}

Answer №2

To prioritize cases in sorting, assign a numerical value to each case and subtract the values when comparing them.

function customSort() {
  const getPriority = ({favorites})=>favorites?.length === 1 ? 0 : !favorites?.length ? 1 : 2;
  const compare = (a, b) => (getPriority(a) - getPriority(b));
  return list => list.sort(compare);
}

const info = [{ rentalName: "Foo", favorites:[{}, {}, {}] }, { rentalName: "Bar", favorites:[{}] }, { rentalName: "Baz", favoriteslikes:[{}] }, { Name: "Plugh", favorites:[] }];

const sortedData = customSort();

console.log(sortedData(info));

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

Is it better to define a function within useEffect or externally?

What is the reason behind defining the fetchData function inside the useEffect instead of outside? Link: https://github.com/zeit/next.js/blob/canary/examples/with-graphql-faunadb/lib/useFetch.js import { useState, useEffect } from 'react' exp ...

Is it possible to send props to a component within the render method?

I have a button component in my render method (DownloadReportsButton) that will trigger a modal onClick and perform an API call. The logic for the modal and the API call have already been moved to the button component, but how do I pass my data (an array ...

Authenticating with passportjs using a Google Apps email address for verification

I am currently experimenting with using Passport.js along with a Google Apps email ID. I have successfully been able to authenticate using a gmail.com email ID, however, I am facing challenges when attempting to authenticate if the email ID is associated w ...

Unable to retrieve the sum total of all product items and display it in the designated text element

My product items are dynamically generated in a list. I have used the calculateItemTotal() method to determine the total for each item. Now, I need to sum up all these item totals and display the result in the total text field. However, instead of showing ...

Tips on deleting specific elements from an array by utilizing the splice method

Here are the details of my first array: [ { members: [ '60ee9148104cc81bec3b97ab' ] } ] And this is the second array: [{"_id": "60ee9148104cc81bec3b97ab","username": "user1", "email": "< ...

The issue of React Js's inline style malfunctioning when using a loop condition

Having some trouble with setting different backgrounds for items in a loop in React JS. I attempted to use inline styles to make it dynamic, but no luck so far. Any tips or solutions? { main.map((item, index) => ( <a key={index} href=&apo ...

Retrieving the response data from a jQuery AJAX call prior to executing the success function

I have a system that relies on AJAX calls through jQuery for data retrieval. My goal is to capture all the received data along with the request details, without altering the existing $.ajax implementations, and forward it to another API for further analysi ...

Unable to establish a connection with the TCP server on CloudFoundry, although the localhost node.js is functioning properly

I am experiencing difficulty connecting to my TCP server example that is running on CloudFoundry. Interestingly, when I run my app.js file on a local node.js installation, everything works perfectly. Upon using vmc push to deploy on CloudFoundry, the servi ...

Challenges with MongoDB related to race conditions or concurrency problems

In the chat application I developed using NodeJS and MongoDB, I have implemented the following code to change the admin for a room: export function setAdmin(room, user) { const userGuid = getGuid(user); if (room.users && room.users.length) { ...

Modifying child text in React when hovering over a button

How can I update the text of a child function component when hovering over a button in the parent class component? I am struggling to access the prop in the child component and keep getting null. Any assistance would be greatly appreciated. Parent Compone ...

Using the `strpos` function in PHP with an array as the needle

I'm trying to verify the mime-type of an uploaded file in PHP and return true if it is allowed. My array consists of certain allowed mime-types, such as: $allowedMimes = array('images','word','pdf'); Where 'images ...

Tips on keeping a div element in a fixed position until triggered by jQuery

I've managed to create a navigation bar within a header that sticks to the top of the screen once you scroll down past 100px. The functionality works well, but I'm looking to make the navigation bar stay fixed on the right until it snaps, essenti ...

Guide on utilizing the where clause to validate the presence of a value in an array within a PostgreSQL database

actName | applicable | status | id | ----------------------------------------------------- example1 | {"applicable":[2,7,8]} | 0 | 3 | example2 | {"applicable":[6,9,5]} | 1 | 4 | Can the presence of a specific value in the ...

php and javascript

On my sales website, when I press the "sales" button, it opens a new frame. There is a chance for multiple frames to be open at the same time. My issue is that I want to close the frame after clicking enter and have the home page updated while keeping al ...

"Seamlessly Integrating AngularJS with WebGL for Stunning Canvas Inter

I am new to AngularJS and curious about its compatibility with HTML5 Canvas or WebGL. Are there any tutorials available on how to integrate AngularJS into a view that uses these technologies? I have noticed some games claiming to be developed with Angular ...

React: When an array state is controlling my components, why aren't they re-rendering?

I am facing an issue with my app where the className of buttons is not updating correctly when clicked. It seems that only active buttons trigger a re-render, while non-active ones do not. This behavior is confusing to me. Here's the code snippet for ...

What is the best way to save a string for future use in Angular after receiving it from a POST request API?

I have been assigned to a project involving javascript/typescript/angular, even though I have limited experience with these technologies. As a result, please bear with me as I may lack some knowledge in this area. In the scenario where a user logs in, ther ...

group items into ranges based on property of objects

I've been grappling with this issue for far too long. Can anyone provide guidance on how to tackle the following scenario using JavaScript? The dataset consists of objects representing a date and a specific length. I need to transform this list into a ...

Safari has trouble with AJAX cross-origin requests, while Chrome and Firefox handle them without issue

I am developing a Shopify app that utilizes script tags and requires an ajax call to our server to retrieve necessary information about the shop. While everything seemed to be functioning correctly, my colleague pointed out that it was not working on his i ...