0

I'd like to check how many elements with name: "order" have value equal 1.

my array:

var myArray=[{"index":1,"zamid":"765","prod":"Spaghetti","price":"22","prod_c":"1","order":"1"},
{"index":2,"zamid":"766","prod":"Coca","price":"5","prod_c":"1","order":"0"},
{"index":3,"zamid":"767","prod":"Hamburger","price":"6","prod_c":"1","order":"1"}]

thank you for help!

luke9999
  • 151
  • 1
  • 3
  • 9

4 Answers4

1

One array method is missing: Array.prototype.reduce()

var myArray = [{ "index": 1, "zamid": "765", "prod": "Spaghetti", "price": "22", "prod_c": "1", "order": "1" }, { "index": 2, "zamid": "766", "prod": "Coca", "price": "5", "prod_c": "1", "order": "0" }, { "index": 3, "zamid": "767", "prod": "Hamburger", "price": "6", "prod_c": "1", "order": "1" }],
    count = myArray.reduce(function (r, a) {
        return r + (a.order === '1');
    }, 0);

document.write(count);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You can use Array.prototype.filter() function (using arrow functions):

let count = myArray.filter(i => i.order === "1").length;

ES5 alternative:

var count = myArray.filter(function(i) {
    return i.order === "1";
}).length;
madox2
  • 49,493
  • 17
  • 99
  • 99
0

You can use Array.filter

var myArray = [{
  "index": 1,
  "zamid": "765",
  "prod": "Spaghetti", 
  "price": "22",
  "prod_c": "1",
  "order": "1"
}, {
  "index": 2,
  "zamid": "766",
  "prod": "Coca",
  "price": "5",
  "prod_c": "1",
  "order": "0"
}, {
  "index": 3,
  "zamid": "767",
  "prod": "Hamburger",
  "price": "6",
  "prod_c": "1",
  "order": "1"
}]

var result = [];

result = myArray.filter(function(obj){
  return obj.order == 1
});

console.log(result)
Rajesh
  • 24,354
  • 5
  • 48
  • 79
0

Define the "outer" counter and check the array with forEach:

var counter = 0;
var myArray=[{"index":1,"zamid":"765","prod":"Spaghetti","price":"22","prod_c":"1","order":"1"},
{"index":2,"zamid":"766","prod":"Coca","price":"5","prod_c":"1","order":"0"},
{"index":3,"zamid":"767","prod":"Hamburger","price":"6","prod_c":"1","order":"1"}];

myArray.forEach(function(obj){
   if(obj.order == 1) counter++;
});

console.log(counter); // output: 2
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105