Combining and organizing two sets of objects in Javascript

I am faced with a challenge of working with two arrays where each element receives a value based on its position within the array. Although both arrays contain the same elements, they are arranged differently. My goal is to calculate the value for each element, merge the arrays into one, and then sort the combined array.

One approach I have in mind involves converting the initial arrays into arrays of objects, merging them, sorting by object value, and then mapping that order into a new array.

var ranks = [],
    objArray1 = [],
    objArray2 = [];

// 'aaa' = 5, 'bbb' = 4, 'ddd' = 3, 'eee' = 2, 'ccc' = 1
var array1 = ['aaa', 'bbb', 'ddd', 'eee', 'ccc'];

// 'ddd' = 5, 'ccc' = 4, 'aaa' = 3, 'bbb' = 2, 'eee' = 1
var array2 = ['ddd', 'ccc', 'aaa', 'bbb', 'eee'];

for (var i = 0, x = 5; i < 5; x--, i++) {
  var obj = {};
  obj[array1[i]] = x;
  objArray1.push(obj);
}

for (var i = 0, x = 5; i < 5; x--, i++) {
  var obj = {};
  obj[array2[i]] = x;
  objArray2.push(obj);
}

// combine both object arrays, match keys, but add values
// should output ranks =[{aaa: 8}, {bbb: 6}, {ccc: 5}, {ddd: 8}, {eee: 3}]

// then sort based on value
// should output ranks = [{aaa: 8}, {ddd: 8}, {bbb: 6}, {ccc: 5}, {eee: 3}]

// then copy keys over to new array while keeping position
// should output var final = ['aaa', 'ddd', 'bbb', 'ccc', 'eee']

Answer №1

If you want to optimize the code, you can avoid using new temporary arrays with objects and simply use a single object for counting and then extract the sorted keys as the final result.

var array1 = ['aaa', 'bbb', 'ddd', 'eee', 'ccc'],
    array2 = ['ddd', 'ccc', 'aaa', 'bbb', 'eee'],
    temp = Object.create(null),
    result;

[array1, array2].forEach(a => a.forEach((k, i) => temp[k] = (temp[k] || 0) - i));
result = Object.keys(temp).sort((a, b) => temp[b] - temp[a]);

console.log(result);

Answer №2

To generate an object, one can utilize the reduce function and then apply sort on Object.keys.

const fruits = ['apple', 'banana', 'orange', 'kiwi', 'grape'];
const sortedFruits = ['orange', 'kiwi', 'apple', 'banana', 'grape'];
const len = fruits.length;

const fruitRanking = fruits.reduce((ranks, item, index) => (ranks[item] = len - index + len - sortedFruits.indexOf(item), ranks), {})
const sortedRanking = Object.keys(fruitRanking).sort((x, y) => fruitRanking[y] - fruitRanking[x])
console.log(sortedRanking)

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

Acquiring JSON-formatted data through the oracledb npm package in conjunction with Node.js

I am currently working with oracledb npm to request data in JSON format and here is the select block example I am using: const block = 'BEGIN ' + ':response := PK.getData(:param);' + 'END;'; The block is ...

Utilizing eval properly in JavaScript

One method I am using is to load a different audio file by clicking on different texts within a web page. The jQuery function I have implemented for this purpose is as follows: var audio = document.createElement('audio'); $(".text_sample ...

Trying to showcase information received from a server using an API

For a school project, I am developing a website that can retrieve weather data (currently just temperature) based on a city or zip code from openweathermap.org using an asynchronous call. I have successfully retrieved the data from the API, but I am strug ...

Add an input element to a form fieldset by employing vue

In my form, I have a staged approach with 3 fieldsets that only appear when the "Next" button is clicked. Now, in the third fieldset, I need to add input elements based on keys extracted from an external json object. Data: data: () => ({ c ...

I'm experiencing a problem when trying to add a document to Firebase Firestore using React Native - it doesn't seem to

I'm currently working on a React Native project that utilizes Firebase v9. My goal is to add a user object to my user collection whenever a new user signs up through the sign-up screen. However, I've encountered an issue where the user object is ...

Performing an asynchronous request within a dynamic helper (or a suitable substitute) in Express version 2.x

I'm attempting to display the total message count for a user's inbox on my website's layout. I initially thought of utilizing Express' dynamicHelpers to achieve this, but in versions of Express <= 2.x, these helpers do not support as ...

What is the reason for the emergence of this error message: "TypeError: mkdirp is not recognized as a function"?

While running the code, I encountered an error indicating that the file creation process was not working. I am seeking assistance to resolve this issue. The code is designed to fetch data from the Naver Trend API and Naver Advertising API, calculate resul ...

Use JavaScript to dynamically populate dropdown list options with array elements

I attempted to populate a dropdown list with array elements using javascript, but I encountered issues. I referred to the following links for assistance: JavaScript - populate drop down list with array use a javascript array to fill up a drop down se ...

Transferring attributes from grandchildren to their ancestor

My React.js application structure looks like this: <App /> <BreadcrumbList> <BreadcrumbItem /> <BreadcrumbList/> <App /> The issue I am facing is that when I click on <BreadcrumbItem />, I want to be able to ch ...

Tips for incorporating a visible marker beside the dropdown arrow

When developing my React application with React hooks forms, I have a select component where I need to include a clear indicator 'x' icon next to the dropdown icon. The current select component code is: <Form.Control size="sm" as=&q ...

The "DELETE" method in ajax is malfunctioning

I encountered an "internal server error (500)" in the console. When checking my NodeJS console, I received a "ReferenceError: request is not defined" message. Below is the code snippet that caused the issue: $(document).ready(function(){ $('.dele ...

Determining button click events in VueJS using the Watch method

Creating a feature for undo/redo in VueJS involves watching the settings and adding a new element to an array of changes when there is a setting change. Additionally, there is a method for undoing actions when the corresponding button is clicked. An issue ...

What is the best way to fetch the most recent article from every category using mongodb?

I am currently working with the following article schema: var articleSchema=new Schema({ id : Number, title : String, sefriendly : String, created : Date, categories: [ { id: Number, name: String, ...

What is the best way to utilize the spread operator across several Vuex modules?

In my search for a solution, I came across another post suggesting that this approach would be effective. However, despite implementing it, I encountered the following error message: 'TypeError: Cannot convert undefined or null to object' comput ...

Validation issue with Reactive Forms not functioning as expected

My latest project involves a user signup component that I created from scratch import { Component } from '@angular/core'; import {UserManagementService} from '../user-management.service'; import {User} from "../user"; import {FormBuild ...

What are the steps to utilizing the $document service in AngularJS?

I am a complete beginner when it comes to AngularJS and JavaScript in general, and I find myself a bit confused about the usage of $document. From what I understand, $document provides access to some JQuery functions. So, if I want to remove an element tha ...

Need help with Swift? Want to learn how to incorporate multiple items into a JSON array?

Currently, I am in the process of developing a simple to-do application for the command-line using Swift. The issue I am facing is that when I try to add a new item to the to-do array, it ends up overwriting the existing entry instead of creating a new one ...

Issue with retrieving data from MySQL database using PHP in Chart.js

I am currently facing an issue while trying to populate a chart using the ChartJS plugin with data from my MySQL database. I keep encountering the error message: mysqli_fetch_assoc(): Couldn't fetch mysqli_result in ... Despite using json_encode, ...

I am unable to halt the relentless stream of asynchronous events

Struggling to retrieve an array using a loop in the asynchronous environment of nodejs. Check out my code below: getDevices(userIDs, function(result) { if (result) { sendNotification(messageUser, messageText, result); res.send("Success"); } else { ...

Need assistance using a form within a popover in Angular UI Bootstrap?

I have implemented a button that triggers an Angular UI Bootstrap popover by using a template. If you want to see it in action, you can check out this demo The popover template consists of a form containing a table with various text fields that are bound ...