Merging two arrays together to create a new array of objects while keeping track of and tally

I'm facing a challenge trying to merge two arrays into an array of objects.

For example:

arr1 = [a,b,c];
arr2 = [a,a,a,b,b,c,d,d];

The desired combination:

combinedArr = [
    {name: a, amount: 3}, 
    {name: b, amount: 2}, 
    {name: c, amount: 1}
];

Note that only values from arr1 should be included, any values in arr2 not present in arr1 are omitted. (in this case, it's "d")

It's worth mentioning that I'm working with After Effect's Extendscript which limits me to the 3rd Edition of the ECMA-262 Standard, hence conventional javascript functions like concat, slice and join are unavailable.

I've made attempts but haven't been able to crack it.. I believe there's a solution involving just a couple of clever loops through the arrays.

Thanks, Simon

EDIT: I see how I may have caused confusion by not sharing my own efforts at solving the problem. My apologies for omitting that, I hastily wrote this question on my phone while traveling.

I've already received some great responses which I appreciate, to clarify my intentions, here's what I initially tried before asking (without simplification, directly from the code):

var createMarkerList = function() {
    var subList = _createMarkerListSub(); //arr1 in this scenario
    var masterList = _createMarkerListMaster(); //arr2 in this scenario
    var output = [];

    for(var i=0;i<subList.length;i++){
        var uniqueMarker = subList[i];
        output.push({
            name: uniqueMarker,
            amount: 0,
        });
    }

    for(var i=0;i<masterList.length;i++){
        var genericMarker = masterList[i];

        if(output[i].name == genericMarker){
            output[i].amount = output[i].amount +1;
        }
    }
}

I want to emphasize that I didn't seek an easy way out by simply asking for the solution without attempting it myself, I genuinely struggled to come up with a solution on my own.

Answer №1

To find the total count of each element in arr1, you must iterate through both arrays.

var arr1 = ['a','b','c'];
var arr2 = ['a','a','a','b','b','c','d','d'];
var combinedObject= {}, combinedArray = [];
for(var i=0; i<arr1.length; i++)
   combinedObject[arr1[i]] = 0;

for(var i=0; i<arr2.length; i++)
   if(combinedObject.hasOwnProperty(arr2[i]))
     combinedObject[arr2[i]]++;

for(var key in combinedObject)
   combinedArray.push({'name': key, 'amount':combinedObject[key]});

console.log(combinedArray);

Answer №2

A hash table can be utilized for counting purposes.

To implement this method, it is necessary to iterate through arr1 in order to create the hash table and result set. After that, a second loop needs to be executed over each item to count and increment the amount property.

var arr1 = ['a', 'b', 'c'],
    arr2 = ['a', 'a', 'a', 'b', 'b', 'c', 'd', 'd'],
    hash = {},
    result = [],
    i;
    
for (i = 0; i < arr1.length; i++) {
    hash[arr1[i]] = { name: arr1[i], amount: 0 };
    result.push(hash[arr1[i]]);
}

for (i = 0; i < arr2.length; i++) {
    hash[arr2[i]] && hash[arr2[i]].amount++;
}

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

Exploring the universal scope in NodeJS Express for each request

I am working with a basic express server that is in need of storing global variables during request handling. Specifically, each request involves multiple operations that require information to be stored in a variable like global.transaction[]. However, u ...

The issue I am facing is that CKEditor is inserting the <pre> tag into my

I have been attempting to input Hindi language content into my database. However, when I make an API request, the data is added in Hindi as needed but a <pre> tag is inserted. I am using CkEditor like this: <CKEditor data={this.stat ...

Ensure that the placeholder remains visible as you type in the input field

Is there a way to implement an input text field in React with the placeholder "DD-MM-YYYY," that partially disappears as I start typing? For example, when I type "02-," only "-MM-YYYY" should remain visible as part of the placeholder. ...

I am unable to utilize ES6 modules alongside typescript in my Node.js project

My Node.js project requires the use of both typescript and es6 modules for compiling files to javascript. The desired outcome is to have the files compiled in javascript with the es6 module. Below is the content of my package.json : { "name": ...

When utilizing multer for handling multipart data, hasOwnProperty appears to become undefined

Below is the code snippet I am currently working with: var express = require('express'); var mongoose = require('mongoose'); var bodyParser = require('body-parser'); var multer = require('multer'); var user = requir ...

Trouble navigating from plugin to theme folder: reference behaving unexpectedly

In a specific wordpress theme, the javascript and jquery files can be found at /functions/extended/js/ Originally, they were located in a plugin folder. I now need to change the references to a folder within the theme. This was my original code: if ( is ...

How to effectively manage the default API quota in YouTube Data API v3 while ensuring requests are made every 60 seconds

Recently, I've encountered a challenge concerning the management of the default API quota for YouTube Data API V3, which allows 10,000 daily requests. In my JavaScript application, I need to fetch the number of subscribers and concurrent viewers every ...

Encountered the issue: "Received the error message 'MongooseServerSelectionError: Server selection timed out after 30000 ms.'"

I encountered the following error: MongooseServerSelectionError: Server selection timed out after 30000 ms while working with MongoDB Atlas. I attempted changing the useUnifiedTopology setting to false, which prevented my application from crashing. However ...

Using React and Ant Design: Sharing state between multiple <Select> components within a <Form> element

Just getting started with ReactJS and AntDesign. Currently, I am working on connecting a series of <Select> components to share state. The goal is for the selection made in the first dropdown to dynamically update the options available in the follow ...

Using body-parser in an Express router: a step-by-step guide

I'm having trouble with a post API that returns an undefined object when trying to print it in the console. I initially thought I was missing body-parser, but even after adding it, I encountered an error message indicating body-parser deprecated bodyP ...

retrieving data into a byte array from the network

In the process of setting up a basic server that waits for a connection and then generates a thread using standard Java code to receive data on that connection. Adhering to a specific protocol outlined by the manufacturer for SOM (Start of Message) and EO ...

Guide to incorporating React component with Postgres database

I'm confused about a scenario where I have created a React project with the command npx create-my-app myProject, and within the public folder, there are multiple folders containing NodeJS for a Postgres database. My question is, if I need to access da ...

Swift: Comparing the functions of addingObjects method versus the append method

I'm in the process of learning Swift 3 for iOS development and I was curious about the distinction between these two methods: if let myItemArray = itemObject as? NSArray { myItemArray.addingObjects(from: [itemTextField.text!]) ...

Solution for dropdown boxes malfunctioning with required fields

Using Bootstrap 3 for field validation on forms has been effective, but there seems to be an issue with certain browsers such as ios safari not validating [required] form items. To address this, I created a script that checks if an element is marked as req ...

Tips on toggling the visibility of div elements with JavaScript

In my selection block, I have three categories of elements and associated Divs. The goal is to display the related divs when a category is selected, while keeping them hidden otherwise. Specifically, I want the husband_name and number_pregnancy divs to be ...

What's the best way to adjust the width of the <Input> component in Reactstrap?

How can I adjust the width of an input element in Reactstrap to be smaller? I've attempted to set the bsSize to small without success <InputGroup> <Input type="text" name="searchTxt" value={props.searchText ...

Retrieve the ReadStream from Firebase Storage and provide it as input to the Openai API

I am struggling to retrieve an image from firebase storage and transmit it to an openai endpoint Here is my current code snippet: const fileStorage = await getStorageAdmin(uid, "/sample.png"); const file = fileStorage.createReadStream(); co ...

Using the Enter key to submit HTML forms

I created a custom console using HTML, CSS, and JavaScript. The input doesn't show up when I press enter, I have to click the send button. How can I make it send on enter press? Here is the code, please assist me: /* code goes below*/ <!DOCTY ...

How can the values from the scale [-60, -30, -10, 0, 3, 6, 10] be converted to a decimal range of 0-1 through

Thank you for helping me with so many of my issues. <3 I'm certain that someone has already solved this, but I'm unsure of the specific mathematical term (I've attempted reverse interpolation and others, but with no luck) so I am present ...

Displaying Kartik's growling animation using AJAX within Yii2 framework

Utilizing kartik growl to display a message via ajax success I attempted the following: This is the javascript code: $.post({ url: "forwardpr", // your controller action dataType: 'json', data: {keylist: keys,user:userdata}, success: f ...