Arranging a list of objects with a designated starting value to remain at the forefront

Consider the array and variable shown below:

array = ['complete','in_progress','planned'];
value = 'planned';

The goal is to always sort the array starting with the 'value' variable, resulting in:

array = ['planned','in_progress','complete'];

For example:

array = ['complete','in_progress','planned'];
value = 'in_progress';

The expected output would be:

array = ['in_progress','complete','planned'];

I have tried various approaches without success. Do you have any concise and efficient ideas?

Answer №1

If you want to prioritize a specific value in sorting, you can do so by checking if it matches one of the arguments and placing it before anything else. If neither item is equal to the specified value, then just proceed with a normal sort.

const array = ['complete','in_progress','planned'];
const value = 'in_progress';

array.sort((a, b) => {
  //a comes first
  if (a == value) return -1;
  //b comes first
  if (b == value) return 1;
  
  //neither matches `value` - compare them normally
  return a.localeCompare(b);
});

console.log(array);

Here's a shorter version achieving the same result by using type coercion:

const array = ['complete','in_progress','planned'];
const value = 'in_progress';

array.sort((a,b) => ((a == value) * -1) || b == value || a.localeCompare(b));

console.log(array);

Answer №2

If I had to suggest something off the top of my head, you could give this a shot:

array = ['complete','in_progress','planned'];
target = 'in_progress';

const answer = array.filter((element) => element !== target)
    .sort()
    .reduce((accumulator, value) => [...accumulator, value], [target]);

An additional note: I completely overlooked the fact that it needs to be sorted.

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

Combining the powers of Nextjs and Vue

Currently utilizing Vue.js, I am now looking to leverage the Next.js framework for its SEO capabilities, server-side rendering features, and other advantages. While I do have some experience with React, my primary focus is on mastering Vue.js. Is it poss ...

What is the best way to trigger a controller action using jQuery in your application.js file?

Currently, I am incorporating the jQuery autocomplete plugin into my project and looking to personalize a specific event: select: function(event, ui) { $('.topic_field').val(ui.item.topic.name); return false; This event es ...

Using JavaScript to convert a UTC Date() object to the local timezone

I am working with a Date() object that holds a UTC date. I need to convert it to the local timezone of the user. Any suggestions on how I can achieve this? Let me know! :-) ...

Update JSON values using JavaScript or jQuery

In the code snippet provided, there is an issue where nameElem.data('index') does not change, causing it to always display element 1 in the list. I attempted to change the json value with cardInfo[i].data.index = index;, but that did not solve th ...

Devising a method to display configurable products as related items along with their customizable options in Magento

I am in the process of creating an e-commerce website using Magento for a client. The issue I am facing is that when I include a configurable product as a related item, it displays the product but without a checkbox. From what I have researched, Magento do ...

Combine two arrays in MongoDB where neither element is null

Issue I am looking to generate two arrays of equal length without any null elements. Solution I have managed to create two arrays, but they contain some null values. When I remove the null values, the arrays are no longer of equal length. aggregate([ ...

Passing a callback function through a prop in Vue.js

Currently, I have a component structured in the following way: <template> <div> <pagination class="center" :pagination="pagination" :callback="loadData" :options="paginationOptions"></pagination> </div> </t ...

Transform an array of objects into a nested tree structure with Javascript

I am currently facing a challenge with handling a complex json file using javascript to structure it hierarchically. My goal is to convert an array of objects into a deeply nested array, where there can be multiple divNames with varying categories and subc ...

HTML/JavaScript - Ways to show text entered into an input field as HTML code

One dilemma I'm facing involves a textarea element on my website where users input HTML code. My goal is to showcase this entered HTML code in a different section of the webpage. How should I approach this challenge? The desired outcome is similar to ...

ReactJS encountered an error: [function] is not defined, July 2017

Attempting to convert a JSON file into an array and then randomly selecting 5 items from it. I suspect the issue lies in my render/return statement at the end of ImageContainer.js, but as a newbie in ReactJS, it could be anything. Any assistance or guida ...

Error 500 on Firebase: Issue solving "firebase" in "firebase.js" not resolved

Struggling to incorporate Firebase into my latest React project, I keep encountering the dreaded "The development server returned response error code: 500." Despite creating a firebase.js file to house my Firebase configuration details, I am at a loss as ...

Using JavaScript to assign one object to another object

I am facing an issue where I am trying to assign the local variable UgcItems to uploadedItems, but when I attempt to return the value, it shows as undefined. If I place the console.log inside the .getJSON function, then I get the expected value. However, t ...

Get the MAC address of a client using Node.js

I have a project in progress that aims to help my home automation system recognize the presence of individuals at home by using their MAC addresses as identifiers. In my attempt to collect the MAC address of a client on my network, I utilized Nodejs along ...

Avoiding metacharacters and utilizing them as a string variable for selection

For example, I have a variable called myid, and its value is "abc xyz". Then, I use a function to escape metacharacters and assign the result to another variable like this: var x = "#"+escapechars(myid);. The evaluated value of x is #abc\\xyz. ...

Using Meteor methods in a Meteor and Ionic application: A guide

After building the web app with Meteor, I am now looking to develop a new app utilizing both Meteor and Ionic technologies. My goal is to leverage the existing Meteor methods in my Ionic app without duplicating efforts for mobile development. Any suggestio ...

Difficulty redirecting Ajax call to a timed-out, CAS-protected server

Our website's login system utilizes CAS for single sign-on. The CAS server is operating the JASIG CAS server at , while our web server runs on Rails at . Due to security reasons, the Rails server has a relatively short session timeout, resulting in o ...

Refresh a TextBox using an Ajax Response

Is there a way to dynamically update a textbox with the response from an ajax call? I've managed to get the response and assign it to the textbox using: document.getElementById("testPad").value = xmlHttpRequest.responseText; The issue is that the en ...

Fill in input field based on choice from the drop-down menu - JavaScript

I am facing an issue where I cannot add text inside the text box based on the dropdown selection. For example, if I select option2 from the dropdown, the textbox should be populated with option2. (function() { 'use strict'; setInterva ...

What is the method for incorporating a variable into a fragment when combining schemas using Apollo GraphQL?

In my current project, I am working on integrating multiple remote schemas within a gateway service and expanding types from these schemas. To accomplish this, I am utilizing the `mergeSchemas` function from `graphql-tools`. This allows me to specify neces ...

Protractor quickly launches and closes the Chrome browser without completing the entire scenario

In order to test my application using protractor, I created a scenario. The application begins with a non-angular login page and then progresses to an angular page after logging in. Here is the javascript code snippet that was utilized: var chai = requir ...