Reorganize array elements in a different sequence utilizing JavaScript

I possess an array

const arr = [
   {label: 'a', width: 200},
   {label: 'b', width: 200},
   {label: 'c', width: 200},
   {label: 'd', width: 200},
   {label: 'e', width: 200}
];

provided with another array

const data = ['d', 'e', 'a', 'c', 'b'];

An arrangement is needed for the first array based on the new data.

Which javascript function should be used for this purpose?

Edit: Appreciating the insightful comments. To add complexity, let's consider that data might not necessarily encompass the entire initial array.

const data = ['a', 'c'];

The resultant array is expected to have 'a' and 'c' as the first two elements, followed by 'b', 'd', and 'e'. The final array should appear in the order of a, c, b, d, e.

Answer №1

  • Utilize the Array#reduce method to loop through the `data` array and store the element-index in a Map
  • With the help of Array#sort, organize the `arr` array based on the value of each element in the previously created Map

const sort = (arr = [], data = []) => {
  const indicesMap = data.reduce((map, e, i) => map.set(e, i), new Map);
  return [...arr].sort(({ label: a}, { label: b }) => {
    const indexA = indicesMap.get(a), indexB = indicesMap.get(b);
    return (indexA === undefined || indexB === undefined) 
      ? isNaN(indexA) - isNaN(indexB)
      : indexA - indexB;
  });
}

const arr = [ {label: 'a', width: 200}, {label: 'b', width: 200}, {label: 'c', width: 200}, {label: 'd', width: 200}, {label: 'e', width: 200} ];
console.log( sort(arr, ['d', 'e']) );
console.log( sort(arr, ['a', 'd']) );
console.log( sort(arr, ['d', 'e', 'a', 'c', 'b']) );

Answer №2

let list = [
  { name: "apple", quantity: 10 },
  { name: "banana", quantity: 5 },
  { name: "cherry", quantity: 20 },
  { name: "date", quantity: 15 },
  { name: "eggplant", quantity: 8 }
];

let selectedItems = ["banana", "apple", "date"];

let updatedList = selectedItems.map((item) => list.find((fruit) => fruit.name === item));
console.log(updatedList);

Answer №3

Put simply:

const list = [
    { name: 'apple', quantity: 10 },
    { name: 'banana', quantity: 5 },
    { name: 'kiwi', quantity: 8 },
    { name: 'orange', quantity: 15 },
    { name: 'grapes', quantity: 3 }
]

const order = ['orange', 'banana', 'grapes', 'kiwi', 'apple']

list.sort((a, b) => order.indexOf(a.name) - order.indexOf(b.name))

console.log(list)

Answer №4

In order to find a solution, apply the map() and find() functions as shown below:

const result = values.map(item =>  list.find(object => object.name === item))

Answer №5

Here is a concise solution utilizing the sort method:

const arr = [
   {label: 'apple', quantity: 10},
   {label: 'banana', quantity: 5},
   {label: 'orange', quantity: 8},
   {label: 'grapes', quantity: 3},
   {label: 'kiwi', quantity: 6}
];
const order = ['orange', 'apple', 'kiwi', 'banana', 'grapes'];

const sortedArray = arr.sort(function(a, b){  
  return order.indexOf(a.label) - order.indexOf(b.label);
});

console.log(sortedArray)

Answer №6

One approach is to assign weights based on the order of elements in a sorted array.

const items = [
   {name: 'apple', quantity: 10},
   {name: 'banana', quantity: 20},
   {name: 'cherry', quantity: 5},
   {name: 'date', quantity: 15},
   {name: 'kiwi', quantity: 8}
];

const priorityOrder = ['date', 'banana', 'apple', 'kiwi', 'cherry'];


items.sort((a, b) => priorityOrder.indexOf(a.name) - priorityOrder.indexOf(b.name))

console.log(items)

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

Supply mandatory argument along with varying arguments to the function

I have a function that requires one parameter and a dynamic set of additional parameters. I am passing an array of blobs to the function. Below is a simplified version of the function: function test(directory, blob0, blob1) { for (var argumentIndex = 1; ...

Struggling with inputting text in an AngularJS application

I am facing an issue with populating a text input with the output of a function in my HTML code. Despite trying different approaches, I am unable to figure out why it is not working correctly. Below is the snippet of my HTML code: <input type="text ...

The active link for pagination in CodeIgniter is malfunctioning

Even though there might be similar posts on StackOverflow, my situation is unique. Hence, I have decided to ask this question with a specific title. Let me break down my issue into smaller parts: Part - 1: I have a regular view page where I can select a ...

A guide on invoking a web method from an aspx.vb page in VB.net

My goal is to call a WebMethod from my aspx.vb file. Below is the syntax of my WebMethod located in Default.aspx.vb: <System.Web.Services.WebMethod()> _ <ScriptMethod(UseHttpGet:=True, ResponseFormat=ResponseFormat.Json)> _ Public Shared Funct ...

Is there a way to retrieve the precise floating-point width of an element?

When attempting to determine the precise width of a table cell, I encountered some discrepancies. While IE9's developer toolbar indicated a width of 203.68px in the Layout tab, using element.clientWidth and other methods yielded a rounded integer valu ...

Struggling to make React respond to button clicks without resorting to using addEventListener

Can anyone help me figure out why I can't get the onclick handler to execute in reactjs when specifying it inline for a button? The only solution that worked for me was using addEventListener. From what I understand, this code should work: <button ...

Error message: Laravel unable to locate requested page

Attempting to make a post request using AngularJS in Laravel, I encountered the following error message: Oops! The page you are trying to access could not be found. JAVASCRIPT app.controller('main',['$scope','$http',&apos ...

Using Typescript, you can specify an array of type <T> within an object

Having a background in JS, I am currently exploring TS. My goal is to create an object with a single field, which is an array of strings, while ensuring strong typing. let container = { items: ['Item 1'] } container.items[0] = 3; // This is i ...

I have to display a pop-up message box after selecting an option from a dropdown menu that fulfills a set of conditions

I am attempting to display a pop-up message when a selection is made on a dropdown menu that meets specific criteria. The dropdown list is generated from a coldfusion output query. I am relatively new to JavaScript, so I may be missing something in my code ...

Create a visual layout showcasing a unique combination of images and text using div elements in

I created a div table with 3 images and text for each row, but I'm struggling to make all the text-containing divs uniform in size. How can I achieve this? Also, I need to center this table on the screen, and currently using padding to do so. Is there ...

Boost the font size on Bootstrap UI Angular timepicker for a better user experience

Is there a way to adjust the font size and width of the timepicker control in Bootstrap UI Angular? Specifically, I am looking to make the text larger and increase the size of the Chevron (up/down buttons). Here is the code snippet I currently have: < ...

Prevented a frame from "https://googleads.g.doubleclick.net" from accessing another frame

After placing ads on my website, they are displaying properly. However, I am receiving an error repeatedly in the console when the page loads: A frame from origin "" is being blocked from accessing a frame with origin "". The requesting frame has an "ht ...

Encountering an issue when attempting to extend a module in nodejs

In my current project, I am developing a module called animal.js that inherits from the color.js module and then is used in the app.js file. Inside Animal.js: var exports = module.exports = {}; exports.animalName = function() { console.log(&apos ...

What is the best way to calculate the number of days between today's date and the end of the current month using Moment.js?

Here's the current code snippet I am working with: const moment = require('moment') const m = moment const currDay = m().format('D') const dayOfWeek = m().format('dddd') const daysInMonth = m().daysInM ...

Blurry text and icons in Bootstrap 3

Does anyone else notice a strange display issue with Bootstrap 3 fonts and glyphicons? It seems like the bitmaps and fonts are appearing blurry on desktops when using Firefox and Chrome, but everything looks fine on mobile devices. I've attached an ex ...

It appears that the crackling noise is being generated by AudioContext.decodeAudioData

I am currently in the process of developing an electron app that enables users to cut and rearrange multiple audio samples while seamlessly playing them back. The combined duration of these samples can exceed an hour, making it impossible to decode and sto ...

Utilize React to extract a JSON object nested within an array and then implement a dropdown sorting feature for the JSON

Can anyone help me figure out how to extract the eventId and title from the "currentSchedule" array nested within the main "response" array? I have successfully looped through all the data in the "response" array dynamically, ...

Troubles with AJAX comment system validation issues

Having created a webpage that displays articles with a textarea under each article for user comments, I implemented AJAX successfully. The validation also works fine - if the textarea is empty, it will display an error and not submit the comment. However, ...

What is the process of integrating data from the OpenWeatherMap API into the WindowInfo feature of Google Maps?

My current project involves retrieving weather information from the openweathermap API and displaying it in an infowindow on Google Maps. However, there seems to be an issue where I am getting data from the previous marker instead of the current one. var ...

How can React and Redux ensure that response data is accessible to every component?

When using react and redux, how can data written in the useDispatch function be made available in other components? Additionally, how can the customerId be accessed in all components? I have created a code that calls an API and returns data in response. I ...