0

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]);
    }
}
1
  • What is f for? Your objects have no .id property, so f[xx[i].id] = xx[i] doesn't make much sense. Did you mean f[xx[i].name]? There's no income variable, so f[income] doesn't make sense, though there is an income property on each xx[i] object, so did you mean xx[i].income or f[xx[i].name].income? Commented Nov 5, 2016 at 15:39

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Why does everyone seem to use .map() all of a sudden instead of .forEach() when the result is ignored? This is a really bizarre trend that's taking place.
1

in ES5 you can use filter to to obtain an array populate with elements having total > 300000

var data = [
  {
    name: "Alex",
    income: 324300,
    total: 30000
  },
  {
    name: "Snake",
    income: 3433000,
    total: 34323000
  }
];
var result = data.filter(x => x.total > 300000);
console.log(result);

4 Comments

Your comment "in ES6 you can use filter..." is wrong. The only reason your solution requires an ES6 compatible environment is the use of the arrow notation.
He's just saying that your suggestion that ES6 is required in order to use filter is wrong. It can be used even in older versions of JS.
OK so I can change my first sentence and write : "in ES5 you can use filter...". That's it ?? I must admit I ve been coding in JS for just 6 monthes and it's difficult to know if it's JS 1 5 or 6
-2

Use filter for this Check this snippet

const xx = [
  {
    name: "Alex",
    income: 324300,
    total: 3030000
  },
  {
    name: "Snake",
    income: 3433000,
    total: 34323000
  }
];
xx.filter(function(item){
  if(item.income>324300)
    alert(item.name);
})

Hope this helps

3 Comments

That it an improper use of filter. Use forEach
Why is it improper?
The function you pass to filter is supposed to return a boolean value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.