Marcos Belunti Marcos Belunti - 1 month ago 6
JSON Question

Javascript count between 2 arrays

I have 2 arrays objects and I need to do a count of home many types of card we have.

The first object contains all the car id's and the second list contains 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"
}]
};


There's only 5 types of cars so I have 5 variables:

var:

ford,
fiat,
mazda,
mini,
mg


So, what I need to end up with is something like this:

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


How can I do this?

Answer

If your number of types are fixed, then try this approach

Make an map first

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

Now iterate the arrays and count by types

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

your map is populated with the values now.

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);

Comments