Reorganizing an array using a custom prioritized list

Is it possible to sort an array but override precedence for certain words by placing them at the end using a place_last_lookup array?

input_place_last_lookup = ["not","in"];
input_array = [ "good", "in", "all", "are", "not", "programmers", "the", "world"]
input_array.sort(function(){/*override*/})
expected_output = ["all", "are", "good", "programmers", "the", "world", "not", "in"]

The words "not" and "in" should be placed at the end based on the lookup array.

Answer №1

If you want to prioritize certain strings in a list, you can compare them with a lookup table first before resorting to normal comparison methods:

let always_last = ["not","in"];
let array = [ "good", "in", "all", "are", "not", "programmers", "the", "world"]
array.sort((a, b) => always_last.includes(a) - always_last.includes(b) 
                  || a.localeCompare(b));
console.log(array);

Key Points:

  • The strings matching the lookup list will be sorted among themselves before other strings.

  • If the lookup array is large, consider using a Set for faster lookups (constant time complexity).

To maintain the order of matches in the lookup array, use indexOf instead of includes:

let always_last = ["not","in"];
let array = [ "good", "in", "all", "are", "not", "programmers", "the", "world"]
array.sort((a, b) => always_last.indexOf(a) - always_last.indexOf(b) 
                  || a.localeCompare(b));
console.log(array);

Sorting with Priority

For sorting items that should come first or last, adjust your comparison logic accordingly:

let always_first = ["programmers"];
let always_last = ["not","in"];

let array = [ "good", "in", "all", "are", "not", "programmers", "the", "world"]
array.sort((a, b) => always_last.includes(a) - always_last.includes(b)
                   || always_first.includes(b) - always_first.includes(a) 
                   || a.localeCompare(b));
console.log(array);

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

Trouble encountered while setting up Firebase Auth for React Native by utilizing AsyncStorage

Trying to implement SMS authentication via Firebase has presented some challenges for me. Despite poring over the documentation and scouring Google for solutions, I've hit a dead end. My setup is pretty basic - just a single input field and a "Send" b ...

Dealing with encoded base64 audio and retransmitting it to Google: a comprehensive guide

I managed to successfully capture audio using the browser's microphone, convert it to base64 encoding, and then sent it over to my node.js application with the intention of further processing it through Google Speech-to-Text API for transcription. How ...

Sending PHP variable to xmlhttp.responseText

I haven't come across this specific situation before, so I thought I would ask for help. My JavaScript code is using AJAX to call a PHP file, run the script in it, and then return a concatenated PHP variable via xmlhttp.responseText to alert that resp ...

Avoiding an endless spiral on a setter in JavaScript/TypeScript

Implementing TypeScript, I've been working on setting up a concept called a "trigger" : an object that includes both a checker function (which returns a Boolean) and a behavior function capable of performing various tasks. My aim is to execute the che ...

Are you in the business of building JavaScript hubs?

I have a unique setup where my express server is in charge of handling all routing and session functionalities. I've envisioned a system where logged-in users can connect to distinct "hubs" based on the location of each hub. My idea was to treat each ...

Developing a collection of reusable components in a Javascript bundle for enhanced efficiency

I currently have a backend rendered page (using Django) that I want to enhance by incorporating components from PrimeVue and a markdown editor wrapped as a Vue component. Previously, we utilized some simple animations with jQuery which we included directly ...

Unusual behavior: Django app not triggering Ajax XHR onload function

I'm currently working on a Django app that features user posts, and I'm in the process of implementing a 'like' / voting system. Initially, I set up this functionality using complete page refreshes combined with a redirect after the vot ...

Using Sweet Alert to enhance the user confirmation experience on your website

I need to replace the standard confirm dialog with a customized one using Sweet Alert. The JavaScript function I want to use is located in the MasterPage. function checkDelete() { swal({ title: "Are you sure?", text: "You will not be able to r ...

React.js encountered an error: Unexpected "<" token

My journey with react.js has just begun. I am currently using Webstorm for development. I have encountered an error that I am struggling to solve. It seems like React is not being recognized even after trying to install various npm react packages. Synta ...

React throwing an error when attempting to include a Link component from react-router-dom

Currently working on a React app and encountering an issue while trying to add the Link component from the react-router-dom package. The main routes are defined in the App.js file structured as follows: https://i.stack.imgur.com/BF8M8.png The <Header ...

FullCalendar displaying inaccurate dates and times

In my ASP.NET MVC application, a full calendar element is displayed as shown below: https://i.sstatic.net/hyAMo.png Here is the JSON data returned by the server through an ajax call for the month of January 2016: [{"id":17,"title":"39/2015 - Site meetin ...

JavaScript and CSS content, when compared, showcase varying characteristics and functionality

I'm attempting to create a conditional statement based on comparing strings from a CSS content attribute. Here is my current code, but despite the strings being identical, the comparison returns false. CSS .right-section::before { content:" ...

Experiencing an unusual issue with grunt: The Gruntfile.js seems to be missing the 'flatten' method

Encountering an unusual error message while attempting to run grunt stated: TypeError: Object Gruntfile.js has no method 'flatten' Being a beginner with node.js, npm, and grunt, I believe my installation of node, npm, and grunt was done correctl ...

Picking out specific elements from a component that is rendered multiple times in a React application

One of the challenges I face involves a component called card, which is rendered multiple times with different data. Here's how it looks: { this.state.response.reminders.map((item,i=0) =>{ return <Card key={i++} reminder={item} deleteRem={th ...

JavaScript payload object's name

Here is the data I have received. {name: "Sinto 6", val: {…}, line: "Sinto 6"} line: "Sinto 6" name: "Sinto 6" val: AvgMachTime: 253 AvgManTime: 1343 CollectMachTimer: 359 CollectManTimer: 108 CycleTimeMach: 359 Cy ...

Issue encountered while utilizing property dependent on ViewChildren

Recently, I designed a custom component which houses a form under <address></address>. Meanwhile, there is a parent component that contains an array of these components: @ViewChildren(AddressComponent) addressComponents: QueryList<AddressCo ...

Automatically Switch Font Colors to Red and Green

I am looking to automate the process of changing multiple textbox colors based on the class property. <input type="text" Class="ChangeColor" /> <input type="text" Class="ChangeColor" /> <input type=& ...

The integration of Node.js and express.js from distinct JavaScript files

How can I utilize express.js to render html in two separate files? file1.js file2.js The code inside file1.js is as follows: var express = require('express'); var app = express(); app.get('/foo/bar1', (req, res) => res.json([&apo ...

Need help incorporating a "section trail" into your website's navigation sidebar using JS/jquery? Here's how you can do it!

My website is quite extensive and contains numerous elements. There are times when I find myself wanting to navigate back and forth between different sections of the page. I've noticed that some websites have a feature called a "page trail," which di ...

How to update router query in Next JS without triggering a page change event

I am seeking a solution to modify a URL query for the current page in Next JS without causing the page change event to trigger. Specifically, I need to be able to remember the week that is being viewed in a calendar, much like how Google Calendar operates. ...