Arrange array items according to the values of two attributes

Within my array of N objects, each object is structured with the following properties:

{
  id: 'an id',
  description: 'a description',
  isUser: true/false
}

My goal is to sort this array based on two criteria:

Firstly, any object whose description contains 'dog', 'cat', or 'animal' should be placed higher in the order. Secondly, if the value of isUser is false, it should also receive priority.

I've found that the standard sort function is not effective for sorting by multiple attributes, so I am seeking guidance on the best approach to achieve this in Javascript (or using Lodash library which I currently utilize: https://lodash.com/)

Answer №1

To prioritize certain strings in the description and move those items to the top, along with any false values of 'isUser'.

var array = [{ id: 1, description: 'cat', isUser: false }, { id: 5, description: 'dog', isUser: true }, { id: 6, description: 'flower', isUser: true }, { id: 7, description: 'cat', isUser: true }, { id: 2, description: 'animal', isUser: false }, { id: 3, description: 'tree', isUser: false }, { id: 4, description: 'dog', isUser: false }];

array.sort(function (a, b) {
    var top = ['dog', 'cat', 'animal'];
    return top.includes(b.description) - top.includes(a.description) || a.isUser - b.isUser;
});

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

Answer №2

var data = [{
  id: '1',
  description: 'a description cat',
  isUser: false
},{
  id: '2',
  description: 'a description bird',
  isUser: true
},{
  id: '3',
  description: 'a description fish',
  isUser: true
},{
  id: '4',
  description: 'a description rabbit',
  isUser: false
}]

function filterData(arr){
  return arr.filter(item => item.description.includes('cat') || item.description.includes('bird') || item.description.includes('fish'))
}

console.log(filterData(data))

Answer №3

Suppose your query involves reorganizing the provided array according to certain properties and conditions.

// group by "description" for animals

const animalGroup = _.groupBy(array, (item) => _.includes(item.description, 'dog') || _.includes(item.description, 'cat') || _.includes(item.description, 'animal'));

// group by "isUser" 
const userGroup = _.groupBy(animalGroup.false, 'isUser');

// final result
const output = [...animalGroup.true, ...userGroup.true, ...userGroup.false]

Answer №4

If you need to customize the sorting of an array, you can provide a compareFunction as an argument to the sort method in JavaScript. This allows you to define your own criteria for how elements should be ordered. Here's an example:

yourArray.sort(function(a, b) {
    if (!a.isAdmin || a.role == 'editor') return -1;
    return 1;
});

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

The automatic opening of a modal in a Livewire component is not functioning as expected

I am having trouble displaying a modal when my component initializes. I have tried using $this->emit('show) to open the modal When I add a button in my view, the emit('show') works! However, I want the modal to be automatically shown whe ...

A guide on iterating through an array in vue.js and appending a new attribute to each object

To incorporate a new property or array item into an existing virtual DOM element in Vue.js, the $set function must be utilized. Attempting to do so directly can cause issues: For objects: this.myObject.newProperty = "value"; For arrays: ...

Looking for a way to assign the (file path to kml) to a variable in your code while utilizing geoxml3?

Is there a way to store the KML file in a variable before parsing it with myParser? Check out this link for more information: https://github.com/geocodezip/geoxml3 var myParser = new geoXML3.parser({map: map}); myParser.parse('/path/to/data.kml' ...

Vue.js has encountered a situation where the maximum call stack size has been exceeded

I have implemented a method called cartTotal that calculates the total price of my products along with any discounts applied, and I am trying to obtain the final value by subtracting the discount from the total. cartTotal() { var total = 0; var di ...

Attention all controllers summoned from one AngularJS document

Having recently delved into the world of AngularJS and Ionic, I've exhaustively searched for solutions both on this forum and beyond. Despite my efforts, nothing seems to be working. My goal is to create an application with a homepage featuring a ser ...

Exploring the varying treatment of the noscript tag across different web browsers

I've been searching everywhere, but I can't find any information on this topic. What I really want to understand is what browsers do with the content inside a noscript tag when JavaScript is enabled. Let's consider an example: According t ...

What could be causing jQuery's Promise.reject to fail?

Currently, I'm dealing with a REST API that resembles this stub: Snippet 1 (example based on Ruby on Rails). I have some existing jQuery code using classic callbacks: Snippet 2 It's running with these logs: case 1: [INFO] /api/my/action1: rece ...

How can you use a single parameter in a JavaScript function to swap the values of two numbers

Here's the challenge I'm facing: I need to create a function that will output 5 when given a(0), and 0 when given a(5). a(0) = 5 a(5) = 0 It should look like this: Hint: Use the following function structure function A(num){} something ...

Experiencing difficulty with passing a jQuery array to PHP

I am trying to pass the values of an array from a JavaScript variable to PHP using AJAX. The issue I'm facing is that after clicking the send button and checking the PHP file to see if the values were passed, it appears empty. However, when I inspec ...

What is the significance of $() in jQuery?

I understand that $() is a selector, but I find it puzzling as to what it actually selects since there is nothing inside the parentheses. Is this a common practice or frowned upon in coding conventions? An example of where I have seen it used is when maki ...

Employing specific delimiters with hogan-express while managing the {{{ yield }}} statement

I've hit a roadblock trying to solve this issue. My goal is to incorporate hogan.js (via hogan-express) into a new expressjs application while also utilizing hogan.js on the front-end with Backbone, lodash, and other tools. The layout I am using cons ...

Is there a way to set a custom width or make the description responsive?

Is there a way to ensure that the description is responsive and automatically goes to the next line instead of extending horizontally? Although using textField could fix this issue, I also need to adjust the padding and outline. Are there any alternative s ...

Trouble with retrieving dates in ISO format

My collection stores the date of birth field in ISO format, for example: ISODate("1980-01-01T20:20:19.198Z") However, when I use a date time picker on my HTML page, it displays the date like this: 01/01/1980 Unfortunately, when querying for the date of ...

What is the best way to update a targeted component in React when triggered by an event handler?

Your goal may seem straightforward, but getting a reference to a specific component using this is proving to be tricky. Here we have our App.js file: import React, { Component } from 'react'; import CoolBox from './coolBox.js'; import ...

Oops! There seems to be a mistake - the provider setPageProvider is not recognized

Struggling to implement pagination on my page using the AngularJS framework. Encountering the error Error: [$injector:unpr] Unknown provider: setPageProvider <- setPage. Despite rearranging the code, the issue persists. Attempted following a tutorial fr ...

Contrasting outcomes when tackling a problem in node.js versus python

After tackling a challenging leetCode problem, I successfully came up with the following solution: Given d dice, each with f faces numbered from 1 to f, determine the number of possible ways (modulo 10^9 + 7) to roll the dice so the sum of the face up nu ...

Typescript's forEach method allows for iterating through each element in

I am currently handling graphql data that is structured like this: "userRelations": [ { "relatedUser": { "id": 4, "firstName": "Jack", "lastName": "Miller" }, "type": "FRIEND" }, { "relatedUser": ...

Utilize esbuild to monitor for any modifications, recompile the code, and automatically restart the express server

In my endeavor to develop a basic SSR-powered project using express + react, I find the need to monitor frontend and backend scripts concurrently in the development process. The primary objective is to utilize express routes in directing to react page com ...

When dragging a new connection in jsPlumb, the existing one should be automatically removed

After using jsPlumb, I was able to create a setup with the following features: Multiple nodes functioning like nodes in a unique flowchart design. Each node has a single target where connections can be dropped. Every node has zero, one, or more exits. Ea ...

What is the best way to transfer attribute values from multiple elements and paste them each into a separate element?

I have multiple elements with the tag <a class="banner2">. Each of these elements has a different URL for the background image and href value. <a href="#" target="_blank" class="banner2" style="background-image:url('<?php echo get_templat ...