Retrieve the size of the attribute of the initial array using a different array

I am working with two arrays

array1 = [
    {name: "samsung", views: 1200},
    {name: "apple", views: 200}
]

array2 = [
    {name: "samsung-1234", views: 200},
    {name: "apple-2332", views: 200},
    {name: "samsung-6543", views: 400},
    {name: "samsung-9876", views: 600}
]

I need to determine how many different types of samsung and apple there are in array2.

Your assistance with solving this problem is greatly appreciated. Thank you!

Answer №1

To create a filter based on the names in array1 and use it on array2, you can utilize the .filter() method. Then, to compare the names, make use of .includes().

let array1 = [
    {name: "samsung", views: 1200},
    {name: "apple", views: 200}
];

let array2 = [
    {name: "samsung-1234", views: 200},
    {name: "apple-2332", views: 200},
    {name: "samsung-6543", views: 400},
    {name: "samsung-9876", views: 600}
];


let result = array1.map(x => ({ name: x.name, total: array2.filter(a => a.name.includes(x.name)).length }));

console.log(result);

Answer №2

To efficiently keep track of occurrences and update the content of array1, consider using a map.

var array1 = [{ name: "samsung", views: 1200 }, { name: "apple", views: 200 }], 
    array2 = [{ name: "samsung-1234", views: 200 }, { name: "apple-2332", views: 200 }, { name: "samsung-6543", views: 400 }, { name: "samsung-9876", views: 600 }]; 
    types = new Map(array1.map(o => ([o.name, Object.assign(o, { types: 0 })]))); 

array2.forEach(({ name }) => ++types.get(name.split('-')[0]).types);

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

Answer №3

Let's use the map function on array1 to filter out elements from array2 based on name matching criteria.

Is this clarification useful for you?

Answer №4

The importance of the initial array is unclear to me, but you can easily determine the number of items associated with Samsung by using a straightforward for loop.

let counter = 0;
arr.forEach((value) => {if (value.brand.match(/samsung/i)) { counter++}})
console.log(counter) // 3

Answer №5

array1 = [
    {name: "samsung", views: 1200},
    {name: "apple", views: 200}
]

array2 = [
    {name: "samsung-1234", views: 200},
    {name: "apple-2332", views: 200},
    {name: "samsung-6543", views: 400},
    {name: "samsung-9876", views: 600}
]

const result = array1.map(brand => {
    let countVariations = array2.filter(ele =>  ele.name.indexOf(brand.name) != -1).length;
    return {name: brand.name, countVariations}
})

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

Encountering a console error: Prop type validation failed for the `Rating` component with the message that the prop `value` is required but is currently `undefined`

I am encountering a proptype error which is causing an issue with the URL display on my Chrome browser. Instead of showing a proper address, I am seeing the URL as undefined like this: http://localhost:3000/order/undefined Instead of undefined, I should h ...

When using jQuery to select elements of a specific class, make sure to exclude the element that triggered the

A dynamic number of divs are generated from a data source. Each div contains an image button and another div with text. While the actual scenario is more complex, we can present a simplified version: <div id="main"> <div id="content_block_1" ...

How can I quickly upload a file while load balancing?

I recently developed an application in node js that includes a load balancing feature. I set up separate servers - one for the database and another for managing requests. The issue arises when users upload files using multer in Express, as the file gets up ...

Steps to retrieve the array values for a specified descendant in a JSON data structure

{ "hasLoadMore": true, "groups": [ { "order": 0, "title": "string", "total": 0, "dateFormat": "string", "messages": [ { "commsId": 0, "commsDirectionCode": "string", "commsReasonCR ...

Optimizing the If operator in JavaScript to function efficiently without causing the page to reload

While delving into jQuery and attempting to create a slider, I encountered a problem. After the slider passed through the images for the second time, the first image would not appear. My approach involved using margin-left to move the images. $(document ...

Is there a way to get an iframe to mimic the behavior of other media elements within a horizontal scrolling container?

Take a look at this code snippet: $(document).ready(function() { $('.scrollable-area').on('wheel', function(e) { var scrollLeft = $(this).scrollLeft(); var width = $(this).get(0).scrollWidth - $(this).width(); var delta ...

Ensure that a synchronous action is performed prior to each Backbone HTTP request

For each authenticated request (GET, POST, etc) in my Backbone/Marionette application, it is necessary to include an accessToken. The accessToken and expireDate are stored in the localStorage. To verify if the accessToken has expired, I utilize the metho ...

Enhancing many-to-many relationships with additional fields in Objection.js

I have a question that I haven't been able to find a clear answer to in the objection.js documentation. In my scenario, I have two Models: export class Language extends BaseId { name: string; static tableName = 'Languages'; st ...

Is using canvas the best option for creating simple image animations with JavaScript?

I am currently working on a basic animation project using JavaScript. This animation involves switching between 13 different images per second to create movement. I have created two simple methods for implementing this animation. The first method involves ...

The username index is not defined in the file path C:xampphtdocsAppX1signin.php on line 6

Experiencing some challenges with a php script I recently created. As a beginner in php, I understand that my code may not be optimal. These error messages are displayed when the form is submitted: Notice: Undefined index: username in C:\xampp&bsol ...

HMR: The webpack-hot-middleware is not refreshing my webpage

My Vue application, titled hello-world, is utilizing webpack-dev-middleware and webpack-hot-middleware. When running the application, it shows that it's connected in the console. However, after making changes to my main.js file, the following message ...

Ways to clear dropdown selection in Vue based on a specific condition?

I am currently developing a dropdown menu for selecting visit status options, which include "pending," "canceled," "rejected," and "approved." In the case of an approved visit status, I would like the dropdown selection to only display the options for "can ...

What is the method for showcasing an image before it has been uploaded?

I must start by apologizing for my English, as I am not the most fluent speaker. Here's where I'm facing a dilemma: I have created an application that allows users to edit questions for a game. These questions are stored on a server and can be ...

What is the process for selecting and clicking a specific div with a distinct class name in HTML

Hey there! I'm a beginner at coding with puppeteer and I have a question. How can I make my code click on this image: (image) The current code I have looks like this: const puppeteer = require('puppeteer'); (async () => { const bro ...

Webpack has issues with loading HTML files

I encountered a 404 not found error while attempting to load the HTML page using webpack. Here are my configurations: Webpack.config.js: const path = require('path'); module.exports= { devServer: { // contentBase static : { ...

What is the most effective way to toggle the visibility of div elements using jQuery?

I am currently working on a small project centered around interviewing people using short GIF animations. I want the viewers to have 10 seconds to watch the GIF, but I've noticed that the timer is not accurate in my code. After some research, I came ...

Aligning text vertically to the top with material UI and the TextField component

Seeking guidance on adjusting vertical alignment of text in <TextField /> const styles = theme => ({ height: { height: '20rem', }, }); class Foo extends React.component { ... <TextField InputProps={{ classes: ...

What is causing the lack of updated data on the components when navigating to a different page? (Vue.JS 2)

I am working with 2 components The first component looks like this : http://pastebin.com/M8Q3au0B Due to the long code, I have used pastebin for it The first component calls the second component The second component is as follows: <template> ...

Combining Arrays in AngularJS: A Step-by-Step Guide

I have two arrays with dynamic values: $scope.objectName = [{ Name: '' }]; $scope.propertiesElement = [{ Key: '', Value: '' }]; How can I concatenate these arrays to achieve the following result? [{Name:''},{ Key: ...

Execute a query to retrieve a list of names and convert it to JSON using Unicode encoding in

Just starting out with Laravel and I'm trying to figure out how to execute some queries Not talking about the usual select statements... I need to run this specific query: SET NAMES 'utf8' First question, here we go: I have Hebrew ...