Ways to retrieve an object with a count of matching elements from two arrays

In order to retrieve an object based on two arrays, the first consisting of unique values and the second containing any values, where the key represents a word and the value indicates the frequency of matches for that word, follow these steps:
For instance:

let uniqueArray = ['green', 'blue', 'red'];

let anyArray = ['red', 'green', 'red', 'blue, 'yellow', 'green', 'pink', 'red'];

The result will be:
{'green': 2, 'blue': 1, 'red': 3}

Answer №1

If you're looking to tally how many times the items in uniqueArray appear in anyArray, here's a neat way to accomplish that:

You can achieve this by employing a reduce method:

let uniqueArray = ['green', 'blue', 'red'];
let anyArray = ['red', 'green', 'red', 'blue', 'yellow', 'green', 'pink', 'red'];

const result = uniqueArray.reduce((data, key) => {
  data[key] = anyArray.filter(x => x === key).length;
  return data;
}, {});

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

Does extracting elements from a session array result in the entire array being deleted in Laravel?

I am currently working on storing an array of values within a session variable. When I want to add a variable, I use the following code: $request->session()->push('some.array', $id); To retrieve the value, I use: $request->session()- ...

What is the best way to extract individual objects from several arrays and consolidate them into a single array?

Currently, I have a collection of objects stored in a variable called listOfObjects. They are not separated by commas because I utilized the Object.entries method to extract these values from another array. console.log(listOfObjects) outputs { q: 'L ...

Determining the width of an element in Chrome using jQuery

Before adding an element to the body, I require its width. The code below functions correctly in Firefox, however it does not work properly in Google Chrome. <style> .testDiv { width:150px; height:100px; } </style> <script> var di ...

What is the best way to center align my horizontal subnav?

I am currently working on a horizontal navbar with horizontal submenus. One issue I am facing is getting the elements in mysubnav to align centrally instead of being pushed to the left all the time. If you need a visual representation of what I mean, plea ...

When the browser is not in the foreground, clicking on the Bootstrap datepicker with Selenium does not register

When you click on the input field <input id="dp1" class="span2" type="text" value="02-16-2012"> If the browser is in the background, the datepicker popup will not display. Even using javascript or jquery to click the input field does not show the ...

Link the Angular Material Table to a basic array

Currently facing a challenge with the Angular Material table implementation. Struggling to comprehend everything... I am looking to link my AngularApp with a robot that sends me information in a "datas" array. To display my array, I utilized the following ...

PHP enables users to look at manual values in columns and MySQL values row by row

I have created a PHP program to organize seating arrangements for an exam hall. The user manually inputs the names of the halls, which should be displayed in columns in a table. The register numbers are fetched from a MySQL database and should be displayed ...

Can Next.js 13 support the usage of axios?

Despite trying to implement the SSG operation with the fetch option {cache: 'force-cache'}, I consistently received the same data even when the mock server's data changed. I found that using the fetch option {cache: 'no-store'} do ...

Backbone "recalling" stored data in attributes

Presented here is a basic model: myTestModel = Backbone.Model.extend({ defaults: { title: 'My Title', config: {}, active: 1, } }) While nothing particularly stands out, there is an interesting observation regardi ...

Navigating through dynamic elements using Selenium

I'm having trouble extracting boxer information from the flashcore.com website using Selenium. The code I've written doesn't seem to be working properly. Can anyone point out where the error might be? The expectation is that Selenium should ...

A Comprehensive Guide on Implementing String Values in Highchart Series

When attempting to pass a string value (data) to the highchart series, I encountered an issue where it would display a blank chart. Is there a specific way to use a string value in the series of the highchart jQuery plugin? var data="{name: 'Jane&apo ...

What is the best way to integrate a React component into an Angular project?

Struggling with integrating a React component into an Angular project and unable to make it work. I have a JavaScript file containing the React component that I want to use in Angular. Here's an example: React file... import React from "react"; c ...

"Exploring the Power of TypeScript Types with the .bind Method

Delving into the world of generics, I've crafted a generic event class that looks something like this: export interface Listener < T > { (event: T): any; } export class EventTyped < T > { //Array of listeners private listeners: Lis ...

How do I extract data from a Firebase object?

Currently, I am facing the challenge of extracting values from an object stored in Firebase. While I have managed to successfully display the entire object in the console: const profile = af.database.object('profile/1'); profile.subscribe(co ...

Are JS promises compatible with any function in Angular?

I have a question: Can you use then() on any function? In my Angular app, I'm encountering an error ('cannot read property then of undefined') when attempting to utilize then. For instance, take this function: self.getCommentsData = funct ...

Transferring seemingly haphazard numerical values from one set to another

My current project involves programming for an embedded board to control the lighting of 4 LEDs out of a total of 8. I am aiming to randomize which LEDs are lit up and repeat this process multiple times. To achieve this, I am copying values from an array o ...

Error: The method 'editable' is not defined for the jQuery.jEditable object [object Object]

It seems like there is an error with this jeditable object. This is my webpage <script src="/assets/jquery.js?body=1" type="text/javascript"></script> <script src="/assets/jquery_ujs.js?body=1" type="text/javascript"></script> .. ...

Problem concerning the window object in a React functional component

Hey there, I am currently facing a situation where I need to access the window object within my React component in order to retrieve some information from the query string. Here is an excerpt of what my component code looks like: export function MyCompone ...

Exploring the dynamic reading of array elements in x86 assembly language for Dos operating system

Is there a different approach to reading an array in a repetitive structure? I am encountering an error with the code below. .data aux db 0 array db 0,1,2,3,4,5,6,7,8,9 .code main: print_array: mov dl, array[aux] mov ah, 02h int ...

What is the best way to start an array in Tcl?

How should an empty array be properly initialized in Tcl? Here is a simplified version of the code: proc parseFile {filename results_array} { upvar $results_array results set results(key) $value } set r1 {} parseFile "filename" r1 But when runn ...