Order an array based on another array using the underscore library in Javascript

I'm trying to align the order of two arrays of objects. Here are the arrays:

Array 1:

var firstArray = [
{id: "1", value: 1},
{id: "5", value: 0.5},
{id: "3", value: 0.25},
{id: "4", value: 0.125},
{id: "2", value: 0.0625}
];

Array 2:

var secondArray = [
{id: 1, name: "a"},
{id: 2, name: "b"},
{id: 3, name: "c"},
{id: 4, name: "d"},
{id: 5, name: "e"}
];

Can anyone help me figure out how to sort Array 2 so that it matches the order of Array 1? The desired result should look like this:

Result:

var secondArray = [
{id: 1, name: "a"},
{id: 5, name: "e"},
{id: 3, name: "c"},
{id: 4, name: "d"},
{id: 2, name: "b"}
];

Answer №1

Here is a solution using Underscore/Lodash, as requested by the question title. This piece of code arranges the second array based on the indexes of the corresponding IDs in the first array.

$(function() {
    var firstArray = [
{id: "1", value: 1},
{id: "5", value: 0.5},
{id: "3", value: 0.25},
{id: "4", value: 0.125},
{id: "2", value: 0.0625}
    ];
    var secondArray = [
{id: 1, name: "a"},
{id: 2, name: "b"},
{id: 3, name: "c"},
{id: 4, name: "d"},
{id: 5, name: "e"}
    ];

    var sorted = _.sortBy(secondArray, function(obj) {
return _.findIndex(firstArray, {id: obj.id.toString()});
    });

    console.log(sorted);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Answer №2

To implement this in plain ES6, you can use a Map to map the index of the given id and then sort it based on the index of firstArray.

However, one challenge is the difference in data types for the id values within the arrays.

var firstArray = [{ id: "1", value: 1 }, { id: "5", value: 0.5 }, { id: "3", value: 0.25 }, { id: "4", value: 0.125 }, { id: "2", value: 0.0625 }],
    secondArray = [{ id: 1, name: "a" }, { id: 2, name: "b" }, { id: 3, name: "c" }, { id: 4, name: "d" }, { id: 5, name: "e" }],
    map = new Map(firstArray.map(({ id }, i) => [+id, i]));

secondArray.sort((a, b) => map.get(a.id) - map.get(b.id));

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

Answer №3

Ever Heard of the XY problem?

It seems like your intention is to establish a relationship between the two arrays by index once the second array is sorted. Allow me to propose a different approach for establishing this relation.

const firstArray =
  [ {id: "1", value: 1}
  , {id: "5", value: 0.5}
  , {id: "3", value: 0.25}
  , {id: "4", value: 0.125}
  , {id: "2", value: 0.0625}
  ]

const secondArray =
  [ {id: 1, name: "a"}
  , {id: 2, name: "b"}
  , {id: 3, name: "c"}
  , {id: 4, name: "d"}
  , {id: 5, name: "e"}
  ]

const thirdArray =
  firstArray.map (x =>
    Object.assign (x, secondArray.find (y => y.id == x.id)))
    
console.log (thirdArray)
// [ { id: 1, value: 1, name: 'a' }
// , { id: 5, value: 0.5, name: 'e' }
// , { id: 3, value: 0.25, name: 'c' }
// , { id: 4, value: 0.125, name: 'd' }
// , { id: 2, value: 0.0625, name: 'b' } 
// ]

Answer №4

By taking note of the different data types in the arrays (one using String for id and the other using Number), a solution can be achieved using ES6 .map() method along with .find():

var firstArray = [
  {id: "1", value: 1},
  {id: "5", value: 0.5},
  {id: "3", value: 0.25},
  {id: "4", value: 0.125},
  {id: "2", value: 0.0625}
];

var secondArray = [
  {id: 1, name: "a"},
  {id: 2, name: "b"},
  {id: 3, name: "c"},
  {id: 4, name: "d"},
  {id: 5, name: "e"}
];

var result = firstArray.map(item => {
  return {
    id: Number(item.id),
    name: secondArray.find(element => element.id == item.id).name
  }
})

console.log(result)

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

Obtain the dimensions (width and height) of a collection of images using Angular and TypeScript

Currently, I am facing an issue with my image upload functionality. My goal is to retrieve the width and height of each image before uploading them. However, I've encountered a problem where my function only provides the dimensions for the first image ...

Implementing tooltips that require a click instead of hovering

How can I make a JavaScript tooltip only appear when clicking on an element instead of hovering over it? I tried the following code: var selection = canvas.selectAll("circle").data(data); selection.enter().append("circle"); canvas.append("svg:circle") ...

Seeking assistance with formatting output for OpenCPU and igraph

Here is my adjacency array data: var g = [[10, 2], [15, 0], [18, 3], [19, 6], [20, 8.5], [25, 10], [30, 9], [35, 8], [40, 5], [45, 6], [50, 2.5]] The code I am using in OpenCPU is as follows: ocpu.call("centralization.closeness", {graph: g} ...

Can a cross-browser extension be developed that integrates with a Python backend for a web application?

Present State I am currently in the initial stages of planning a web application that users will access through a browser extension designed as a horizontal navigation bar. My initial plan was to utilize Pylons and Python for this project, but I am uncert ...

Displaying File Name Discrepancies within an Array of Items (Java)

I have encountered an issue while trying to compare files. My current solution works well for folders containing a small number of files, around 10. However, it fails when dealing with folders that have over 200 filenames. The problematic part of my code ...

What is the method for extracting a list of properties from an array of objects, excluding any items that contain a particular value?

I have an array of objects, and I want to retrieve a list with a specific property from those objects. However, the values in the list should only include objects that have another property set to a certain value. To clarify, consider the following example ...

What could be the reason why I am unable to choose my radio button? What error am I

The output can be found here... I am struggling to use a radio button and cannot seem to select it. Can someone please explain what issue I am facing? Any help would be greatly appreciated. const [value, setValue] = React.useState({ yes:"", no:"" ...

Having trouble retrieving data from the database when passing input to a mongoose query using an href tag in Node.js

Welcome to My Schema const AutomationSchema=new mongoose.Schema( {EventName:String, EventDate:String, EventLocation:String, EventDetails:String } ) The Events Model const EventsModel=new mongoose.model("Events",AutomationSchema ...

When I attempt to run several promises simultaneously with Promise.All, I encounter an error

My code contains a series of promises, but they are not being executed as expected. Although the sequence is correct and functional, I have found that I need to utilize Promise.all in order for it to work properly. dataObj[0].pushScreen.map(item => { ...

Modifying the attribute of an element inside an array

Presented below is an object: { "_id" : ObjectId("5a8d83d5d5048f1c9ae877a8"), "websites" : [ "", "", "" ], "keys" : [ { "_id" : ObjectId("5a8d83d5d5048f1c9ae877af"), "name ...

Converting an object with a combination of different index types into a string representation

I'm dealing with a unique object structure that behaves similarly to an array, except it contains a mix of index types (numbers and strings). Here's an example: var myObj = []; myObj[0] = 'a'; myObj[1] = 'b'; myObj[2] = &apos ...

Dividing an array into three separate groups

I am looking for a solution to partition an array of integers into 3 sets in such a way that the sum of elements in each set is as close as possible to each other. Here is the method I have come up with: Start by sorting the array in decreasing order In ...

Is there a way to set a custom width or make the description responsive?

Is there a way to ensure that the description is responsive and automatically goes to the next line instead of extending horizontally? Although using textField could fix this issue, I also need to adjust the padding and outline. Are there any alternative s ...

I am unable to access the properties of an undefined element, specifically the 'size' property in Next.js 13

I encountered a problem today while working with Next.js version 13.4 and backend integration. When using searchParams on the server side, I received an error message: "Cannot read properties of undefined (reading 'size')" while destructuring siz ...

Is there a way I can replace this for loop with the array.some function?

I am looking to update the filterOutEmails function in the following class to use array.some instead of the current code. export class UsertableComponent { dataSource: MatTableDataSource<TrialUser> createTableFromServer = (data: TrialUsers[], ...

Creating data representations using classes

As a new programmer, I'm struggling to model the following program in code. The program involves reading a file, filtering specific data, and displaying it. I've attempted to use arrays and functions as shown in my textbook, but I can't seem ...

Convert numpy C array into a C double* [] and then reverse the process

After facing challenges, I successfully imported a numpy array into C and was able to return an empty numpy array of the same size. Now my goal is to perform a convolution using a 3x3 kernel. My approach involves creating a separate C function to handle th ...

Exploring the potentials of REST services using the .Net 2.0 framework in conjunction with integrating REST consumption in JavaScript

According to Wikipedia, REST is defined as REST is considered to be the architectural style of the World Wide Web. It was developed alongside the HTTP/1.1 protocol, while building upon the design of HTTP/1.0 The practices of REST have been in existence ...

Updating records in MySQL using jQuery and PHP through an inline method

I'm using JQuery/Ajax and php/MySQL to perform CRUD operations. Currently, I can insert/select and delete data without any issues. However, I'm facing a challenge with the edit/update functionality. When I try to edit data and click on the save ...

In Javascript, the function sets a Boolean value to true but unexpectedly returns false

I have encountered an issue with my Audio Player. I created it in the document ready and set a variable for playing to false. However, even though the function seems to be called correctly, it does not set that variable to true as expected. The code for ...