Calculate the number of elements shared between two arrays using JavaScript

I am working with two arrays of objects and I need to determine how many different types of cars we have.

The first array contains the IDs of all the cars, while the second array contains information about the types of cars.

Here is the data:

var arr = {
    "categories": [{
        "id": "100",
        "name": "category name",
        "car_id": "1"
    }, {
        "id": "192",
        "name": "category name here",
        "car_id": "25"      
    }, {
        "id": "192",
        "name": "category name here",
        "car_id": "27"      
    }]
};


var arr2 = {
    "cars": [{
        "id": "1",
        "name": "car name",
        "car_id": "1",
        "type": "ford"
    }, {
        "id": "4",
        "name": "name 2",
        "car_id": "25",
        "type": "ford"      
    }, {
        "id": "4",
        "name": "name 2",
        "car_id": "27",
        "type": "fiat"      
    }]
};

Since there are only 5 types of cars, I have created 5 variables:

var:

ford,
fiat,
mazda,
mini,
mg

My goal is to end up with something like this:

ford: 2;
fiat: 1;
mazda: 0;
mini: 0;
mg: 0;

Can someone guide me on how to achieve this?

Answer №1

For a fixed number of types, consider using this method

Create a map initially

var map = {
  ford: 0,
  fiat: 0,
  mazda: 0,
  mini: 0,
  mg: 0
};

Then go through the arrays and tally up the types

arr2.cars.forEach(function(item) {
  map[item.type]++;
});

Your map now contains the counts by type.

var arr2 = {
  "cars": [{
    "id": "1",
    "name": "car name",
    "car_id": "1",
    "type": "ford"
  }, {
    "id": "4",
    "name": "name 2",
    "car_id": "25",
    "type": "ford"
  }, {
    "id": "4",
    "name": "name 2",
    "car_id": "27",
    "type": "fiat"
  }]
};
var map = {
  ford: 0,
  fiat: 0,
  mazda: 0,
  mini: 0,
  mg: 0
};

arr2.cars.forEach(function(item) {
  map[item.type]++;
});

console.log(map);

Answer №2

const categoryArr = {
    "categories": [{
        "id": "100",
        "name": "category name",
        "car_id": "1"
    }, {
        "id": "192",
        "name": "category name here",
        "car_id": "25"      
    }, {
        "id": "192",
        "name": "category name here",
        "car_id": "27"      
    }]
};

const carArr = {
    "cars": [{
        "id": "1",
        "name": "car name",
        "car_id": "1",
        "type": "ford"
    }, {
        "id": "4",
        "name": "name 2",
        "car_id": "25",
        "type": "ford"      
    }, {
        "id": "4",
        "name": "name 2",
        "car_id": "27",
        "type": "fiat"      
    }]
};

let carCount, typeCount;

categoryArr.categories.forEach(function(item){
    if(item.hasOwnProperty("car_id")){
         carCount = categoryArr.categories.length;
    }
});

carArr.cars.forEach(function(item){
    if(item.hasOwnProperty("type")){
         typeCount = carArr.cars.length;
    }
});

console.log(carCount);
console.log(typeCount);

https://jsfiddle.net/Law7rzc2/

Answer №3

Everything you require is

calculateTotal(arr2.cars, 'type')

The completion of calculateTotal is a task for the reader.

Answer №4

Array.prototype.reduce is the ideal function to use for performing array computations like this. Utilizing a Map can assist in keeping track of the distinct car makes as you loop through the array of cars.

var obj2 = {
    "cars": [{
        "id": "1",
        "name": "car name",
        "car_id": "1",
        "type": "ford"
    }, {
        "id": "4",
        "name": "name 2",
        "car_id": "25",
        "type": "ford"      
    }, {
        "id": "4",
        "name": "name 2",
        "car_id": "27",
        "type": "fiat"      
    }]
};

const typeStat = cars => {
  let map = cars.reduce((m, {type}) =>
    m.set(type, (m.get(type) || 0) + 1), new Map());
  return Array.from(map, ([make, count]) => ({make, count}));
};

let stats = typeStat(obj2.cars)

console.log(stats);

Output

[
  {
    "make": "ford",
    "count": 2
  },
  {
    "make": "fiat",
    "count": 1
  }
]

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

Modifying the src attribute of an object tag on click: A step-by

So I have an embedded video that I want to dynamically change when clicked on. However, my attempt at doing this using JavaScript doesn't seem to be working. <object id ="video" data="immagini/trailer.png" onclick="trailer()"></object> H ...

Guide to parsing JSON into model objects using Spring's RestController

My current project involves developing a RESTful web application with the Betfair API. To achieve this, I am dealing with JSON serialization/deserialization to handle HTTP requests and responses effectively. As part of my setup, I have opted for Spring MV ...

Repetitive cycling through an array

My array consists of classes: const transferClasses = [ { id: "c5d91430-aaab-ed11-8daf-85953743f5cc", name: "Class1", isTransfer: false, children: [], }, { id: "775cb75d-aaab-ed11-8daf-85953743f5cc", ...

Tips for organizing a search using two keys in Javascript

I am dealing with a large dataset containing over ten thousand objects that hold information about two different ids as shown below: dataSet = [ { ids: ["123", "234"], information: 1 }, { ids: ["123", "345"], in ...

Exploring methods to deactivate specific dates within the angular material datepicker

Is it possible to prevent specific dates from being selected based on the current date? For example, if today is 8/1/16, I would like to disable the next 4 days (any number of days could be chosen), excluding weekends. So, if today is 8/1/16, I would want ...

Troubleshooting V-model errors within VueJS components

Just dipping into VueJS and trying out a chat feature from a tutorial. I noticed the tutorial uses v-model in a component, but when I replicate it, the component doesn't display on the screen and the console throws a "text is not defined" error. Strug ...

Incorporate Angular directives within a tailor-made directive

I just started using a fantastic autocomplete directive called Almighty-Autocomplete. However, I feel like it's missing some features. The basic structure of the directive is as follows: .directive('autocomplete', function () { var index ...

Developing a Secondary User within Meteor.JS after Establishing the Primary User

Is it possible to automatically create a secondary user upon registration of the primary user using a form generated with the useraccounts:core package? An issue arises when attempting to run Accounts.createUser within Accounts.onCreateUser, resulting in ...

Populating a table with information retrieved from a file stored on the local server

Here is the specific table I am working with: <div class="chartHeader"><p>Performance statistics summary</p></div> <table id="tableSummary"> <tr> <th>Measurement name</th> <th>Resul ...

Tips for excluding a non-serializable field from json.dumps in Python

Serializing the output of parsing binary data using the Construct2.9 library and converting it to JSON has proven to be a challenge for me. packet is an instance of the Construct class Container. Upon inspecting the output of dict(packet), I discovered t ...

Monitor the change in FileReader().readyState using AngularJS

Below is the AngularJS code I have written to read a local file. var files = document.getElementById("file"); files.addEventListener("change", handleFile, false); function handleFile(event) { SpinnerService.upload(); // Display loading spinner ...

Using local storage with github sites can lead to some unexpected and peculiar behavior

Currently, I am working on a simple clicker game using HTML and JavaScript. To store the variables money and taxCollecters, I have implemented local storage. However, I am encountering strange issues when trying to use the save and load buttons on the Gi ...

A guide on implementing nested child routes in AngularJS 2

I have successfully completed routing for two children, but now I want to display nested routes for those children. For example: home child1 child2 | grand child | grand child(1) ...

Retrieve the JSON response from the server and store it in variables using jQuery's AJAX function with the `done

I am trying to retrieve a JSON response from the server upon clicking a button and then parse it into a div. However, I am struggling with how to accomplish this. <button type="submit" id="btPay" name="btPay"> Go for Pay ...

Dynamic way to fetch computed properties in VueJS

I am trying to find a way to calculate the sum of computed properties that begin with the string calculateSum. The challenge is that I cannot access their names using this.computed. Here is my approach: getSubTotal(){ var computed_names = []; var ...

Create movement in line art using the position of the cursor

I have created a skull lineart in illustrator and I am trying to make the lines fill in or erase based on mouse position. There are two possible ways to achieve this: Using lazy line painter to draw the lines and then finding a way to animate based on ...

Generate a complete screenshot of a website using Chrome 59 through code

Is it possible to programmatically capture a full-page screenshot of a website using the latest Chrome 59 and chromedriver with Selenium Webdriver, even if the website is larger than the screen size? ...

Is there a way to prevent the back button from functioning in my web browser?

How can I prevent the back button from being used on my webpage? Can you provide a list of possible methods to achieve this? if($data->num_rows > 0){ while($row = $data->fetch_assoc()){ header('Location:../cashier.php&apo ...

Incorporate an onclick event to the elements within the array

I'm currently working on iterating over an array and adding an onclick event to each element. My goal is to be able to click on each div and have them log their values in the console. However, I am facing a challenge in applying the onclick event to e ...

My Special Character is not encoded by JSON

Within my database table, there are two fields present: Title = Testing Title Description = CREDITO FISCAL OCDE CFDI AMPAROS REVISIÓN ELECTRÓNICA REGLAMENTO ISR RIF ID: 44 However, when I receive the json response, it always returns with a null descrip ...