1

This is my first question in stackoverflow, So any kind of help is appreciated.

I have an array like this

var products = [{status:'available', ...},{status:'none', ...},{status:'available', ...},{status:'', ...},{status:'none', ...}]

how can I get an array that contains only products[i].status = 'available' .

I already did this with for loop but isn't there a better method? My code is practically full of loops now & it's not easy to read.

Thank you for you help.

  • 3
    use `filter()` function, `var res = products.filter(v => v.status == 'available')` – Pranav C Balan Nov 16 '17 at 09:38
  • 1
    Here is the documentation for`filter`: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter – ADreNaLiNe-DJ Nov 16 '17 at 09:39
  • Can you please elaborate ? –  Nov 16 '17 at 09:39
  • Possible duplicate of [Javascript: How to filter object array based on attributes?](https://stackoverflow.com/questions/2722159/javascript-how-to-filter-object-array-based-on-attributes) – Melchia Nov 16 '17 at 09:41

6 Answers6

4

Use Array.filter method

products.filter(function(product){
    return product.status == 'available'
})
Dean
  • 668
  • 12
  • 32
4

Using arrow functions (ES6) is a shortest one

products.filter(product => product.status == 'available')

Will return an appropriate array of products where statuses arr "available"

Mikhail Katrin
  • 2,304
  • 1
  • 9
  • 17
1

Try this

var products = [{
  status: 'available'
}, {
  status: 'none'
}, {
  status: 'available'
}, {
  status: ''
}, {
  status: 'none'
}]

var array = $.map(products, function(value, index) {
 

  if (value["status"] == "available") {
    return [value];
  }

});

console.log(array);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Nisal Edu
  • 7,237
  • 4
  • 28
  • 34
1

https://jsfiddle.net/dvwu75ja/

Try This one

var products = [{status:'available'},{status:'none'},{status:'available'},{status:''},{status:'none'}];
x = 0;
products.forEach(function(element) {

    if(element["status"] == "available"){
       //code here, x is just to represent what index you are in now
        console.log(x);
    }
    x++;
});

Hopes this help

Rey Norbert Besmonte
  • 791
  • 2
  • 12
  • 29
1

var products = [{status:'available'},{status:'none'},{status:'available'},{status:''},{status:'none'}];
for(var i = 0; i < products.length; i++){
if(products[i].status == products[0].status){
 console.log(this.products[i]);
}
}
vicky patel
  • 699
  • 2
  • 8
  • 14
0

Using ES5 most broswer support this one:

products.filter(function(product){return product.status === 'available'})

Using ES6 works too but not all browser support ES6 yet:

products.filter(product => product.status === 'available')
Melchia
  • 22,578
  • 22
  • 103
  • 117