What is the best way to arrange an array by the attribute of related elements in another array using Javascript?

Imagine I have two sets of items. The first set is:

A = [apple, banana, cherry, date]

and the second set is,

B = [watermelon, xigua, yuzu, zucchini]

Each item in A corresponds to the respective item in B

(i.e. apple -> watermelon, banana -> xigua, cherry -> yuzu, date -> zucchini)

Now I aim to arrange the items in A in ascending order based on a certain property (let's say size) of the items in B

(e.g. watermelon.size = 3, xigua.size = 2, yuzu.size = 1, zucchini.size = 4)

So, I want the output to be:

[cherry, banana, apple, date]

How can I achieve this using JavaScript? Any assistance would be greatly appreciated as I've been struggling with this for quite some time.

Answer №1

To achieve this, you can obtain the indices, arrange them based on the values of variable b, and then map the values of variable a by utilizing the sorted indices.

var a = ['a', 'b', 'c', 'd'] ,
    b = [3, 2, 1, 4],
    indices = [...b.keys()].sort((x, y) => b[x] - b[y]),
    result = indices.map(i => a[i]);

console.log(result);

Answer №2

To get the desired outcome, implement the following method which involves using indexOf and sort.

  1. Arrange array - a by sorting it based on the values from array b using the indexOf method.

var a = ["a", "b", "c", "d"]
var b = [3, 2, 1, 4]

console.log(a.sort((x,y) => b[a.indexOf(x)] - b[a.indexOf(y)]))

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

How can we ensure that multiple forms are validated when submitting one form in AngularJS?

Is there a way to validate two forms on the same page (address1 and address2) using AngularJS when the button on one of the forms is clicked? ` ...

Unable to extract all advertisements from Facebook Marketplace

https://i.stack.imgur.com/xEhsS.jpg I'm currently attempting to scrape listings from Facebook marketplace, however, only the first listing is being scraped. Does anyone have any suggestions on how I can scrape the entire list of listings? CODE (async ...

Submitting a POST request using a Chrome Extension

I am in the process of developing a Chrome extension popup for logging into my server. The popup contains a simple form with fields for username, password, and a submit button. <form> <div class="form-group"> <label for="exampleInputE ...

Manipulate classes based on scrolling (Wordpress)

Trying to manipulate a widget by adding and removing classes based on user scroll behavior has proven to be quite challenging. Specifically, I aim to add one class when the user scrolls down by 50px and remove it when they scroll back up. Website: Check o ...

Order of execution for Angular 2 components

import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms'; import {Router, ActivatedRoute, Params} from '@angular/router'; import { Country } from &ap ...

Having trouble retrieving AJAX response data using jQuery

I have been searching and attempting for hours without success. On my current page, I am displaying basic data from a database using PHP in an HTML table. However, I now want to incorporate AJAX functionality to refresh the data without reloading the page ...

Disconnection between client and server communications

Can communication between two entities be established in this scenario? For example, if a server receives a file upload and determines it is incorrect, can it send an event to the client? The client would then catch the event and manipulate the DOM to dis ...

pick out particular values from an array

I have a question that may seem basic to some, but I'm curious about how to select specific elements from an array. In this case, I have an array with 100 elements: var cubes = [element1, element2, element3 ...] and I want to select elements 25-35. ...

Ways to confirm non-null values and bypass the row if it is

I have been attempting to compare 2 dates in order to appropriately display data in a table. I have tried the following approach: ${this.dateToCompare.getTime()} > ${row.CreateDate.getTime()} However, there is an issue where CreateDate has a null value ...

Struggling with React Js and need some assistance?

I'm completely new to React Js and encountering issues with my code. Here's what I have: Here is the content of my script file named Main.jsx. This file gets compiled by React, and the output is stored in main.js under the 'dist' folde ...

Employ the faker.js library to automatically create a form within casperjs environment

When using Casperjs to fill and submit forms, it is necessary to manually input the data each time. On the other hand, Faker.js can generate fake data that can be used in forms. The question then arises - how can these two be combined effectively? Consider ...

VUE JS - My methods are triggering without any explicit invocation from my side

I've encountered a frustrating problem with Vue JS >.<. My methods are being triggered unexpectedly. I have a button that is supposed to execute a specific method, but this method gets executed along with other methods, causing annoyance... Her ...

experimenting with a TypeScript annotation

I have created a simple decorator that can trigger either stopPropagation() or preventDefault() based on certain conditions. I have thoroughly tested this decorator in my application and am confident that it works correctly. However, I encountered an issue ...

Issues encountered when implementing server-sent events in a project built with Node.js and React

I've been working on implementing server-sent-events into my Node.js and React application. After doing some research and following tutorials online, I found this particular site to be very helpful and straightforward. The main objective is to have a ...

fnRedraw and fnReloadAjax do not have the capability to refresh the datatable

I have been working on updating a table with new data from an ajax url. The table loads correctly the first time, but I am struggling to get it to refresh. $(function() { var datepicker = $( "#date-picker" ); var table = $("#reports1").dataTable( ...

When HTML elements are dynamically inserted through JavaScript using quilljs, they may cause conflicts with the layout properties

I am currently working on creating a simple webpage layout similar to that of Stack Overflow, with a sidebar and a main content area that can scroll. In my case, the content area is intended to host a QuillJS text editor. To integrate the QuillJS editor i ...

The successful Ajax POST request does not result in an update to the JSON file

I am facing an issue with adding data to a *.JSON file. Despite receiving a "success" message from Ajax, the file remains unchanged. I have also noticed that when the JSON file is empty, nothing happens at all. Can someone help me find a solution? I'm ...

guide on launching react with pure javascript

Is it feasible to operate react "straight out of the box" using only JavaScript? In essence, I am seeking a way to utilize react by simply utilizing notepad to create the page (without needing to install and configure node etc.). More specifically - 1) ...

React is throwing an error that says, "You cannot use the import statement outside a

My journey with learning React has just begun. I followed the steps outlined in the starting guide at https://react.dev/learn/add-react-to-an-existing-project, but unfortunately, I encountered an error: "Cannot use import statement outside a module." Here ...

Causing a click event to occur results in crashing the browser

Take a look at this link: example on jsfiddle Why does the click event keep triggering multiple times when a div is clicked, eventually causing the browser to crash? What could be causing this issue and how can it be resolved? The actual div contains a l ...