zzz zzz - 1 month ago 9
Javascript Question

Filter objects array

I got an array like this:

const xx = [
{
name: "Alex",
income: 324300,
total: 3030000
},
{
name: "Snake",
income: 3433000,
total: 34323000
}
];


I want to check if the income is larger than 300000 and if it is then their name would be stored or logged.

This is what i have tried, i dont fully understand how it works so..

var f = {};
for (var i = 0, len = xx.length; i < len; i++) {
f[xx[i].id] = xx[i];
if(f[income]>=500000){
console.log(xx[i]);
}
}

Answer

You can use Array.filter for filtering the array and Array.forEach for iterating over it to console.log or w/e you want to do with it.

const xx = [
  {
    name: "Alex",
    income: 324300,
    total: 3030000
  },
  {
    name: "Snake",
    income: 3433000,
    total: 34323000
  },
  {
    name: "Wake",
    income: 4,
    total: 3
  }
];

xx.filter(function(x) {
  return x.income > 30000;
}).forEach(function(x){
  console.log(x)
});