Sort an array based on the values contained in a separate array using Javascript

I am working with two arrays of objects:

arr1 =  [{chart: {field: "test", title: "ABC", type: 0}}, {chart: {field: "test", title: "123", type: 1}}, {chart: {field: "test", title: "XYZ", type: 2}}]

arr2 =   [{Name: "XYZ"}, {Name: "ABC"}, {Name: "123"}]

Is there a way to sort arr2 based on the values found in the title property of arr1?

The intended result should look like this:

[{Name: "ABC"}, {Name: "123"}, {Name: "XYZ"}]

Answer №1

To arrange the elements in an array, you can utilize the built-in sort method along with findIndex(). The sort() function is used based on the index obtained. I have implemented a shared function called func to retrieve the index of both arguments for sorting.

const arr1 =  [{chart: {field: "test", title: "ABC", type: 0}}, {chart: {field: "test", title: "123", type: 1}}, {chart: {field: "test", title: "XYZ", type: 2}}]


const arr2 =   [{Name: "XYZ"}, {Name: "ABC"}, {Name: "123"}];

const func = a => arr1.findIndex(b => b.chart.title === a.Name);

const res = [...arr2].sort((a,b) => func(a) - func(b));

console.log(res)

Answer №2

Rather than sorting arr2, update its values based on the values in arr1:

[{chart: {field: "test", title: "ABC", type: 0}}, {chart: {field: "test", title: "123", type: 1}}, {chart: {field: "test", title: "XYZ", type: 2}}].map(item => ({"Name" : item.chart.title }) );

Answer №3

If you're looking to keep track of indices, a helpful tool could be using a Map.

var array1 = [{ chart: { field: "test", title: "ABC", type: 0 } }, { chart: { field: "test", title: "123", type: 1 } }, { chart: { field: "test", title: "XYZ", type: 2 } }],
    array2 = [{ Name: "XYZ" }, { Name: "ABC" }, { Name: "123" }],
    indices = new Map(array1.map(({ chart: { title }}, i) => [title, i]));

array2.sort(({ Name: a }, { Name: b }) => indices.get(a) - indices.get(b));

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

Answer №4

To generate a fresh array of arr2 based on the contents of arr1, you simply need to use the map method with a callback function.

arr2 = arr1.map((item) => ({Title: item.chart.title}));

Appreciate your help!

Answer №5

Check out this potential solution:

arr1 =  [{chart: {field: "test", title: "ABC", type: 0}}, {chart: {field: "test", title: "123", type: 1}}, {chart: {field: "test", title: "XYZ", type: 2}}]

arr2 =   [{Name: "XYZ"}, {Name: "ABC"}, {Name: "123"}]

var newArr = [];
arr1.filter(item=>{
  newArr.push(arr2.find(element => element.Name === item.chart.title));
});

console.log(newArr);

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

AngularJS - Always keep an eye on a group of items

Looking to create a custom watcher for a collection within my application, I initially believed that Angular would have all the necessary tools at my disposal. I had access to $watch, both shallow and deep, as well as $watchCollection. A $digest cycle was ...

Is it possible to attach an EventListener to an <option> element?

I have been attempting to attach an EventListener to an <option> Element. Despite trying various methods, I have not seen any success so far. I am currently working with VueJS, and I attempted to utilize their event-binding mechanism. VueJS - Event ...

SCRIPT5007: The property 'href' cannot be assigned a value as the object is either null or undefined

This script is functioning properly in browsers like Chrome and Firefox, however it is encountering issues when used with Internet Explorer. An error message is displayed in the IE console: SCRIPT5007: Unable to set value of the property 'href': ...

Angular-Chart.js - Issue with Tooltip not displaying for data points with a value of 0

Within my Angular Chart JS Application, I have encountered an issue where having "0" values in my data array seems to affect the functionality of the tooltip for the corresponding bar. Interestingly, changing the "0" values to "0.1" resolves the problem... ...

Accessing external data in Angular outside of a subscription method for an observable

I am struggling to access data outside of my method using .subscribe This is the Service code that is functioning correctly: getSessionTracker(): Observable<ISessionTracker[]> { return this.http.get(this._url) .map((res: Response) => ...

Activating radio button based on the value in a text field

When the value is set to "Runner", the radio button will be enabled. If the value is anything other than "Runner", the radio button will be disabled. However, the code provided below seems to always disable the button, which is not the intended behavior. ...

"Exploring the world of jest.doMock: A guide to mocking

Here is the code snippet I am testing: ... import data from '../data/mock.json'; // function is async export const something = async () => { try { ... if (!data) { throw 'error is here!'; } ...

Discovering the value of a chosen star and saving it in a database with the help of jQuery or JavaScript

When a user clicks on the 3rd star in the Jrate Plugin, I need to retrieve the value of 3. This can be achieved using the jRate onSet option. Below is my HTML: <div id="jRate"></div> And this is my JavaScript code: $("#jRate").jRate({ ...

Jquery Triggers Failing to Work Following Ajax Request

I have worked on 2 PHP pages, called "booking.php" and "fetch_book_time.php". Within my booking.php (where the jquery trigger is) <?php include ("conn.php"); include ("functions.php"); ?> $(document).ready(function(){ $(".form-group"). ...

Creating a Django-powered Ajax auto page loader

I am working on a website that would greatly benefit from having an autopager feature. An autopager automatically loads the next page when scrolling to the bottom, similar to how the Reddit Enhancement Suite functions. However, implementing this in Django ...

What happens in mongoose if one of several consecutive queries fails?

Currently, as I work on my API, I am utilizing two Models: SongModel and UserModel. Whenever a new song is saved, I also execute a query to link the song._id to the user who created it. Unfortunately, a mistake in my code caused the second query to throw a ...

The formset's submit button fails to function properly when it is dynamically created through ajax requests

In order to update my models, I am using a formset and displaying forms based on the search query. I have an ajax keyup function that sends post requests to generate search_results.html, which is then passed into search.html. However, when I dynamically g ...

Arranging PHP multidimensional array based on their IDs

Is there a way to sort a multidimensional array based on another array that specifies the desired order? The $lookingfor array contains the preferred order, while the $avaliableArray holds the complete multidimensional array. The expected output should be ...

Incorporating the "+ " icon in Vuejs Dropzone to indicate the presence of existing images

Looking to enhance my Vue-dropzone file uploader component by adding an icon or button labeled "Add more images" when there are already images present in the dropzone. This will help users understand that they can upload multiple photos. Any suggestions on ...

Struggling to get a basic HTML form to function with JavaScript commands

In my form, there are two input fields and a button. Upon clicking the button, a JavaScript function is triggered which multiplies the values entered in the inputs. The result is then displayed in a <p> element and evaluated through an if else statem ...

How to enhance a class in JavaScript by adding a dynamic property

Within my code, I've defined a class which looks like this: class classA { id: number; name: string; constructor(data){ this.id = data?.id || 0; this.name = data?.name || ''; } } What I aim to do now is add ...

React Context Matters: Troubles Unleashed

I've been facing some difficulties with passing a value from one file to another. The problem seems to be related to implementing context, but I can't seem to figure out where I went wrong! import React from 'react' const Mycontext = ...

Creating JSX elements in React by mapping over an object's properties

I need to display the properties of an object named tour in JSX elements using React without repeating code. Each property should be shown within a div, with the property name as a label and its value next to it. Although I attempted to iterate over the o ...

Javascript: Understanding Error Handling in the Context of Async Await

I am looking to strengthen my logical reasoning, not diving into abstract concepts. Scenario 1: try { var result = await new IamErrorAlways() if (result && result instanceof Error) return result // Is this the appropriate error handling method? } ca ...

How can I convert base64 data to a specific file type using React Cropper JS?

I have successfully implemented the crop functionality using react cropper js. Now, I am faced with a challenge of sending the cropped image as a file type. Currently, I can obtain the base64 string for the cropped image. However, when I submit the cropped ...