Arranging array based on the sequence of another array

There are two arrays that I am working with:

Main array:

const items = [
  "Лопата 123",
  "Empty Forest",
  "Forever young",
  "My ears",
  "Most Important",
  "16 Tons",
  "Operation Flashpoint",
  "Prize A1",
  "Нарешті літо",
];

And keys array:

const keys = ["Prize A1", "Forever young", "Most Important"];

The goal is to sort the main array based on the order of the keys array, like this:

const expected = [
  "Prize A1",
  "Forever young",
  "Most Important",
  "Лопата 123",
  "Empty Forest",
  "My ears",
  "16 Tons",
  "Operation Flashpoint",
  "Нарешті літо",
]

I tried to write some code to achieve this, but it's not working correctly:

const expectedOrder = items.sort(function(a, b) {
   return keys.indexOf(b) - keys.indexOf(a);
});

 const items = [
    "Лопата 123",
    "Empty Forest",
    "Forever young",
    "My ears",
    "Most Important",
    "16 Tons",
    "Operation Flashpoint",
    "Prize A1",
    "Нарешті літо",
  ];
    
const keys = ["Prize A1", "Forever young", "Most Important"];

const expectedOrder = items.sort(function(a, b) {
   return keys.indexOf(b) - keys.indexOf(a);
});

console.log('expectedOrder', expectedOrder)

Answer №1

To organize the items, consider using a default value of -1 for indices.

 const
     items = ["Лопата 123", "Empty Forest", "Forever young", "My ears", "Most Important", "16 Tons", "Operation Flashpoint", "Prize A1", "Нарешті літо"],
     keys = ["Prize A1", "Forever young", "Most Important"];

items.sort((a, b) => ((keys.indexOf(a) + 1) || Number.MAX_VALUE) - ((keys.indexOf(b) + 1) || Number.MAX_VALUE));

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

A more concise method involves using an object for sorting with a default value.

 const
     items = ["Лопата 123", "Empty Forest", "Forever young", "My ears", "Most Important", "16 Tons", "Operation Flashpoint", "Prize A1", "Нарешті літо"],
     order = { "Prize A1": 1, "Forever young": 2, "Most Important": 3, default: Number.MAX_VALUE };

items.sort((a, b) => (order[a] || order.default) - (order[b] || order.default));

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

Answer №2

Locate the positions of your keywords:

  • "Prize A1" = 0
  • "Forever young" = 1
  • "Most Important" = 2

Arranging the items in a certain order depending on their value relative to a reference value, for example "Prize A1" < "Most Important"

You can reverse the order of your keywords list:

const items = [
    'Лопата 123',
    'Empty Forest',
    'Forever young',
    'My ears',
    'Most Important',
    '16 Tons',
    'Operation Flashpoint',
    'Prize A1',
    'Нарешті літо',
];

const keywords = ['Prize A1', 'Forever young', 'Most Important'].reverse();

const expectedOrder = items.sort(function(a, b) {
    return keywords.indexOf(b) - keywords.indexOf(a);
});

console.log('expectedOrder', expectedOrder);

Answer №3

To maintain the original order of the list, it is important to verify if the items are present in the keys array.

If both items are either included or not included in the keys array, then their positions remain unchanged. However, if only one of the items is included in the keys array, it should be arranged before the other item in the list.

 const items = [
    "Лопата 123",
    "Empty Forest",
    "Forever young",
    "My ears",
    "Most Important",
    "16 Tons",
    "Operation Flashpoint",
    "Prize A1",
    "Нарешті літо",
  ];
    
const keys = ["Prize A1", "Forever young", "Most Important"];

const expectedOrder = items.sort(function(a, b) {
   const incA = keys.includes(a);
   const incB = keys.includes(b);
   
   return (incA === incB)? 0 : ((incA)? -1 : 1);
});

console.log('expectedOrder', expectedOrder)

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 there a way to transform row results into an array similar to array($result)?

I am struggling to add my row result to an array like array($output_variable). Here is what I have tried: <?php require('init.php'); session_start(); $result = mysqli_query($conn, 'SELECT item_name , quantity FROM books WHERE ...

Error: JSON encountered circular structure when attempting to serialize an object of type 'ClientRequest' with a property 'socket' that references an object of type 'Socket'

Encountering an error while attempting to make a POST request to my TypeORM API using axios: TypeError: Converting circular structure to JSON --> starting at object with constructor 'ClientRequest' | property 'socket' -&g ...

Reveal content as you scroll

I'm having trouble with the code snippet below. My goal is to utilize .cbp-fbscroller in my CSS to show a new side navigation menu on my HTML page only when scrolling down to 900px. However, as someone who is new to JavaScript, I am struggling to make ...

Using jQuery/Javascript to create a dynamic content slider

I am currently working on developing a straightforward content slider. When the page loads, my goal is to display only one item (including an image and some content) and provide a navigation system for users to move through the items. Below is the basic H ...

Is there a way to change the background color of the body on click and have it applied throughout the entire site

Is there a way to change the background-color of the entire site and specific modal elements when a user switches between two radio buttons? Here is the HTML code for the radio buttons: <div class="btn-group btn-group-xs" data-toggle="buttons"> ...

The technique of accessing parent props from a child composition component in React

I am trying to reduce every letter prop from the child component, Palata. How can I achieve this? index.js <Block letter="I" mb={16}> <Palata letter="I" start={4} end={9}/> <Wall/> <Empty/> <Palata le ...

Is there a way to use Javascript or JQuery to conceal all unchecked items in a RadioButtonList?

Currently, I am utilizing the Asp .net repeater to bind the selected value in the RadioButton list. Here is an example snippet: <asp:RadioButtonList ID="RadioButtonList1" runat="server" SelectedValue='<%# Eval("Numbers& ...

Can TypeScript modules be designed to function in this way?

Seeking to create a versatile function / module / class that can be called in various ways: const myvar = MyModule('a parameter').methodA().methodB().methodC(); //and also this option should work const myvar = MyModule('a parameter') ...

Is it possible to dynamically group by one column in a dataset without requiring a trigger function?

I've been working on a script that retrieves values from another page and organizes them into a table alphabetically by Name, City, and District. The current script is functioning well, but I now want to enhance it by grouping the values by city as we ...

Texture on plane is not displaying properly in Three.JS

Seeking assistance! I've been struggling all day to successfully load a texture onto my plane in Three.JS. Every time I attempt to add the desired link, it either fails or *poof* my plane disappears mysteriously. Please lend me your expertise with Thr ...

The code is triggering IE 8 to switch to compatibility mode resembling IE7

I have created a custom javascript function that generates a pop-up, and I am invoking this function in my code. However, every time I click the button, the browser switches to IE 7 compatibility mode and the pop-up appears behind the button. Below is my ...

PHP Session Array Replication

I am facing an issue while setting a session array with pre-defined values, where users can then add to it using a simple HTML form. The problem arises when the page is refreshed or revisited, as the pre-defined values in the array are duplicated each time ...

While working with Ngrx/effects, an error with code TS2345 occurred. The error message stated that the argument is of type 'Product[]', which cannot be assigned to a parameter of type

When I compile my code, I encounter the following issue (despite not finding any errors in the browser console and the application functioning properly). An error occurs in src/app/services/product.service.ts(15,9): The type 'Observable<Product> ...

What is the best way to store XHR data in a browser's cache?

I have been seeking a solution to locally cache an XHR request on my computer for future use. Whenever I visit an online shop, I often encounter a form in the order page that includes a field with XHR. After filling out this field, I have to submit the f ...

Tips on customizing regex to selectively identify specific strings without capturing unrelated ones

Currently, I am working with this regex: /(?<=^|\/)(?:(?!\/)(?!.*\/))(.*?)[:-]v([\d.-]+)(?=\.|$)/ The goal is to extract the captured group from the following strings: rhmtc/openshift-velero-plugin-rhel8:v1.7.9-4 oc-mirror-plug ...

Nuxt - issue with updating window innerwidth getter

The class based components in our project utilize a getter to retrieve the window innerWidth. However, I've noticed that the value is only set once and doesn't update if the window width changes. get viewPortWidth() { if (process.client) { ...

Ways to conceal <td>s in angularjs on specific rows during ng-repeat

In the first <tr>, I have a table with many <td> elements that I am populating using ng-repeat. <tr ng-repeat="receipt in $data"> <td data-title="voucher number"> <span>{{receipt.voucher_no}}</span> </td ...

The sendKeys() method is malfunctioning in Selenium WebDriver

When attempting to enter phone numbers into the designated field, an error is being encountered. Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element The following code snippet is involved: driver.get("https://m ...

Is there a way to repurpose a function to work with both ids and classes?

My current code is affecting all elements instead of just the intended one. I've experimented with classes and ids, ruling out those as potential issues. I'm hoping for my JavaScript to target only the selected element, not all of them. Check ou ...

obtain the equivalent offsetX value for touch events as for mouse events

Greetings! I am currently attempting to retrieve the offsetX and Y values of a touch event, which ideally should match the offsetX value of a mouse event. In order to achieve this, I have implemented the following code: ev.offsetX = ev.targetTouches[0].p ...