Conditional VUE array count

Asked

Viewed 438 times

6

I need to find out how many records of the array below has the active field as true, how can I do?

[ { "name": "Quero Vender", "active": false }, 
{ "name": "Quero Comprar","active": false } ]
  • You just want the count or you want to know what you have active === true ?

2 answers

8


TL;DR

You can use the method Array.reduce() to return a sum of the 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 parameter of the method. The accumulator is quite confused as "previous item" where they use reduce in 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, for the first is the sum of 1 + 2 that was the accumulated value and the second is the 3rd item of the array that contains the value 3.

It’s a common mistake and so I always advise you to name as acc or anything that reminds you that is a accumulator to avoid confusion.

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

[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"

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

In this case, I’m only taking the property value active of the object as it is the only information I need from it. Ex.:

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

And finally I take advantage of the fact that convert boolean values to Number generate values 1 and 0 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 from the previous information it is 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

3

You can do something like

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.