Unshifting values in a JavaScript array only if they exist in another array

I have two arrays of objects - one containing selected data and the other containing general data that needs to be displayed

General data for display

const arr = [
  {
    id: "1",
    name: "Skoda - Auto"
  },
  {
    id: "2",
    name: "BMW - Auto"
  },
  {
    id: "3",
    name: "Mustang"
  },
  {
    id: "2",
    name: "Ferrari"
  },
  {
    id: "1",
    name: "Ford"
  }
];
selectedValues 

const selectedArr = [
  {
    id: "1",
    name: "something - 1"
  },
 {
    id: "3",
    name: "something - 1"
  }
]

I need to rearrange the general data array based on the selected values array. The goal is to prioritize the items in the general array that match the ids in the selected array and move them to the top. Expected Output:

const arr = [
  {
    id: "1",
    name: "Skoda - Auto"
  },
  {
    id: "1",
    name: "Ford"
  },
  {
    id: "3",
    name: "Mustang"
  },
  {
    id: "2",
    name: "BMW - Auto"
  },
  {
    id: "2",
    name: "Ferrari"
  },
];

There may be multiple values with the same id, which should all be moved to the top if they exist in the selected array. I am not sure how to achieve this, so any help would be greatly appreciated.

Answer №1

To achieve this, you can create a mapping of indices for each ID in the sorting array:

const selectedArr = [
    {
        id: "1",
        name: "item - 1"
    },
    {
        id: "3",
        name: "item - 2"
    }
]

const sortMap = new Map(selectedArr.map(({ id }, index) => [id, index]));

Then, utilize this map in the standard sort function by creating a copy of the array using [...arr] to avoid mutating the original array. Items not found in the sortMap will be given a high index to place them at the end...

const sortedArray = [...arr].sort(
    (itemA, itemB) => (sortMap.get(itemA.id) ?? 10000000) - (sortMap.get(itemB.id) ?? 10000000)
);

Playground Link

const arr = [{
    id: "1",
    name: "Toyota - Car"
  },
  {
    id: "2",
    name: "Honda - Car"
  },
  {
    id: "3",
    name: "Chevrolet"
  },
  {
    id: "2",
    name: "Tesla"
  },
  {
    id: "1",
    name: "Hyundai"
  }
];

const selectedArr = [{
    id: "1",
    name: "something - 1"
  },
  {
    id: "3",
    name: "something - 1"
  }
]

const sortMap = new Map(selectedArr.map(({
  id
}, idx) => [id, idx]));

const sortedArray = [...arr].sort((a, b) => (sortMap.get(a.id) ?? 10000000) - (sortMap.get(b.id) ?? 10000000));

console.log(sortedArray)

Answer №2

An alternative approach, albeit not the most efficient one, involves filtering the array twice - once to extract the selected elements and another time to gather the non-selected ones. These two filtered arrays are then concatenated together. The code snippet below illustrates this process.

const selected = [4, 8, 3];
const fullArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const sorted = fullArray.filter((e) => selected.includes(e))
.concat(fullArray.filter((e) => !selected.includes(e)));

console.log(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

Using Reactjs to Send Emails

Trying to incorporate the SmptJs API for email sending using JavaScript has been quite successful in a simple HTML setup. However, I am facing challenges when attempting to integrate it into a ReactJs component! The API documentation and link can be found ...

Acquiring an icon of a program using its handle

I am looking for a way to extract a program's icon from its handle, which I acquired using User32.dll with EnumWindow/FindWindow. While I am aware of ExtractAssociatedIcon, it seems to work from a file instead of a handle. My question is how can I con ...

Choose a specific <div> element from an external page using Ajax/PHP

I'm encountering a small issue. I am currently utilizing Ajax to dynamically load content from another page into a <div> element after detecting a change in a <select>. However, my specific requirement is to only load a particular <div& ...

Maintain the visibility of the jQuery dropdown menu even when navigating to a different page within the

I am experiencing an issue with my dropdown menu. Whenever I click on a "dropdown link", it opens another page on my website, but the menu closes in the process. I want to ensure that the menu stays open and highlights the clicked "dropdown link" in bold. ...

A guide to assigning multiple classes to an element in Vue.js depending on the props!

Take a look at my code to grasp the issue. <template> <div class="header" :class="flat ? 'flat' : null" :class="app ? 'app' : null"> </div> </template> <script> export default ...

Converting Large XLSX File (over 600MB) to CSV Using Node.js

Currently, I am facing an issue with converting a large XLSX file, which is over 600mb in size, to CSV format. The conversion process works perfectly fine with smaller files that are less than 3MB. However, when it comes to larger files, the program star ...

"Using Bootstrap's toast feature repositions every element on the

I am working on a website project and encountering an issue with a bootstrap toast. The toast currently appears in the top right corner, but I would like it to display above the carousel without affecting the layout. Instead, when the toast appears, it shi ...

What is the method to incorporate type hints for my unique global Vue directives?

When I import or create a directive in an SFC file, I can receive TypeScript hints like this: import vFocus from 'my-custom-component-library'; View demo with ts hints However, if I globally register it in main.ts, the type hints are not availa ...

Reload the text content of a locally hosted webpage within an iframe at regular intervals

I have set up a simple webpage on my local machine to showcase the contents of some text files on a dedicated monitor. However, I am facing an issue where refreshing the entire webpage causes flickering. My goal is to only refresh the iframes and reload t ...

Utilizing Vue CLI plugin to dynamically pass JS variables as props

I am currently using version 4.5 of the Vue CLI plugin. I have created a component that takes in a title as a prop. This component has been converted into a web component and added to an HTML webpage (which is not a Vue JS project) Now, I am attempting to ...

When utilizing the `express.static(__dirname)` function in Node.js with Express, the visitor may be directed to an incorrect HTML page

My website consists of a login page named login.html and an index page named index.html. I want to implement authentication so that only logged in users can access the index page. I have not set up the post method on the login HTML page. Therefore, I have ...

An issue has occurred where all parameters for the DataService in the D:/appangular/src/app/services/data.service.ts file cannot be resolved: (?, [object Object])

Upon running the command ng build --prod, an error is encountered. Error in data.service.ts: import { BadInput } from './../common/bad-input'; import { AppError } from './../common/app-error'; import { Injectable } from '@angular ...

Initiate an "execute.document" command directly from the address bar

While reviewing my old website, I stumbled upon this snippet: <input type="image" id="QuickPass" name="QuickPass" src="/images/QuickPass.gif" alt="Quick Pass" onclick="document.pressed=this.value" value="QuickPass" /> nestled within this form: & ...

Encountered a 404 error while utilizing the Java - Angular web service

Encountering an error 404 in Firebug when attempting to send an object from Angular to a Java controller using JSON. While the backend in Java is able to receive the message, Angular is unable to find the specified path. Consequently, there is an issue wit ...

What is the correct data type for the vuex store that is passed to the vuex plugin when it is being initialized?

Here is how the store initialization process is currently being implemented: /* Logic */ import Vue from 'vue' import Vuex, { StoreOptions } from 'vuex' Vue.use(Vuex) const DataManager = new UserDataManager() type RootStateType = { ...

An issue is preventing the Angular 2+ http service from making the requested call to the server

I am looking to create a model class that can access services in Angular. Let's say I have the following endpoints: /book/:id /book/:id/author I want to use a service called BooksService to retrieve a list of Book instances. These instances should ...

Send back alternate HTML content if the request is not made via AJAX

Last time I asked this question, I received several negative responses. This time, I will try to be more clear. Here is the structure of a website: Mainpage (Containing all resources and scripts) All Other pages (HTML only consists of elements of that ...

Do these two JavaScript statements behave the same under the principles of functional programming in a React environment?

Is there a rule in functional programming that states these two approaches are equivalent? When working on a React application, I initially passed a function as an attribute using the second version where the first parameter is also passed. Out of curiosi ...

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 ...

Record modified fields using Angular Reactive Forms and store them in a list

Is there a method available that can identify and return the fields that have been modified within a form? I am looking to generate a list of string values for the changed fields. I am dealing with a complex form containing approximately 30 different fiel ...