'JavaScript: How to filter data in an array
I have following object in JS:
[
{
"financial_year":1,
"mainline_revenue":18743.0,
"regional_revenue":2914.0,
"other_revenue":3198.0,
"non_operating_items":-1983.0
},
{
"financial_year":2,
"mainline_revenue":20218.0,
"regional_revenue":3131.0,
"other_revenue":3394.0,
"non_operating_items":-3233.0
},
{
"financial_year":3,
"mainline_revenue":30802.0,
"regional_revenue":6322.0,
"other_revenue":5526.0,
"non_operating_items":-1367.0
}
]
financial_year is the unique identifier which I want to use to filter data. How can I filter data where for example financial_year is 2 and put the other values in an array?
Solution 1:[1]
You can use the filter
method on arrays. filter
takes a callback which returns true or false (more accurately, a truthy or falsey value). If it returns true, that object is included in the resulting array.
let input = [
{
"financial_year":1,
"mainline_revenue":18743.0,
"regional_revenue":2914.0,
"other_revenue":3198.0,
"non_operating_items":-1983.0
},
{
"financial_year":2,
"mainline_revenue":20218.0,
"regional_revenue":3131.0,
"other_revenue":3394.0,
"non_operating_items":-3233.0
},
{
"financial_year":3,
"mainline_revenue":30802.0,
"regional_revenue":6322.0,
"other_revenue":5526.0,
"non_operating_items":-1367.0
}
];
let output = input.filter((obj) => obj.financial_year !== 2);
console.log(JSON.stringify(output, null, 2));
Or rewritten with ES5:
var input = [
{
"financial_year":1,
"mainline_revenue":18743.0,
"regional_revenue":2914.0,
"other_revenue":3198.0,
"non_operating_items":-1983.0
},
{
"financial_year":2,
"mainline_revenue":20218.0,
"regional_revenue":3131.0,
"other_revenue":3394.0,
"non_operating_items":-3233.0
},
{
"financial_year":3,
"mainline_revenue":30802.0,
"regional_revenue":6322.0,
"other_revenue":5526.0,
"non_operating_items":-1367.0
}
];
var output = input.filter(function(obj) {
return obj.financial_year !== 2;
});
console.log(JSON.stringify(output, null, 2));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mike Cluck |