Array count in VUE with conditional

5

I need to figure out how many records in the array below have the field active as true, how can I do it?

[ { "name": "Quero Vender", "active": false }, 
{ "name": "Quero Comprar","active": false } ]
    
asked by anonymous 13.12.2018 / 21:14

2 answers

7

TL; DR

You can use the Array.reduce() method to return a sum of items, adding 1 when active is true and 0 otherwise.

dados.reduce((acc, {active}) => acc + !!active, 0)

Explanation

The method Array.reduce(callback, initialValue) iterates over an array and saves in a "variable" the result of each iteration. This variable is called accumulator and its initial value is defined in the second method parameter. The accumulator is quite confused as "previous item" where they use reduce it this way:

[1, 2, 3].reduce((anterior, atual) => anterior + atual)

In the last step of the above code, anterior will equal 3 and atual will also be 3 , since the first is the sum of 1 + 2 that was the accumulated value and the second is the 3rd array item that contains the 3 value.

It's a common mistake and so I always advise naming it as acc or anything that reminds you that it's an accumulator to avoid confusion.

And remember that if the accumulator value is not defined, the first value of the array will be used and will throw an error if the array is empty (after all, there is no first element in an empty array). Some examples of usage:

[1, 2, 3].reduce((acc, num) => acc + num)     // 6
[1, 2, 3].reduce((acc, num) => acc + num, 0)  // 6
[1, 2, 3].reduce((acc, num) => acc + num, 10) // 16
[1, 2, 3].reduce((acc, num) => acc + num, "") // "123"

Upon receiving the array item I am using (acc, {active}) => ... which is a feature of ECMAScript 2015 Destructuring assignment which allows me to grab only the parts I need from an object or array.

In this case, I'm only getting the value of the active property of the object because it's the only information I need it. Ex.:

let obj = {nome: "Teste", active: true}
let {active} = obj
console.log(active)  // true

And lastly I take advantage of the fact that convert Boolean values to Number generate 1 and 0 values for true and false , respectively.

console.log(Number(true))  // 1
console.log(Number(false)) // 0

I also use the ! operator to convert the value to a boolean.

console.log(!!1)  // true
console.log(!!0)  // false

Knowing the previous information makes it easier to understand that the code creates an accumulator with value 0 and sum 1 when active === true , arriving at the result that is an active item counter.

Code working:

let dados = [
  {name: "Quero Vender", active: false},
  {name: "Quero Comprar", active: false}
]

let count = dados.reduce((acc, {active}) => acc + !!active, 0)

console.log(count)  // 0

// Adiciona alguns items ativos
dados.push({name: "Teste", active: true})
dados.push({name: "Teste 2", active: true})

count = dados.reduce((acc, {active}) => acc + !!active, 0)

console.log(count)  // 2
    
13.12.2018 / 22:04
6

You can do something like this

let meuArray = [
  { "name": "Quero Vender", "active": false },
  { "name": "Quero Comprar","active": false },
  { "name": "Quero Tudo","active": true },
  { "name": "Quero Nada","active": true }
]

let contaActive = (array) => {
  let numeroDeActive = 0
  
  array.forEach(element => {
    if (element.active === true) numeroDeActive++
  })

  return numeroDeActive
} 

console.log(contaActive(meuArray))

As you are using VueJS , instead of declaring a function, you can use a method or computed , then it will depend on your need.

>     
13.12.2018 / 21:22