I have an array that contains a bunch of random elements such as:
[{
"id":332,
"foo":6,
"event":"ABC-CNEG Correlations Ed3.0 Update 9 (XY-AHZ)",
"date":"2018-11-26T00:00:00.000Z",
},
{
"id":324,
"foo":1,
"event":"ABC 3166-1_2013 No. VII-11",
"date":"2018-06-30T00:00:00.000Z",
},
{
"id":325,
"foo":1,
"event":"ABC 3166-2_2013 To. XII-32",
"date":"2018-06-30T00:00:00.000Z",
},
{
"id":326,
"foo":2,
"event":"ABC 3166-1_2016 No. VII-12",
"date":"2018-06-30T00:00:00.000Z",
},
{
"id":327,
"foo":1,
"event":"ABC 3166-2_2018 To. XII-31",
"date":"2018-06-30T00:00:00.000Z",
}]
What I need to do is "cherry pick" the above items and create a new array that contains ONLY the items that contain the following string: 3166-1. So, the expected output would be:
[
{
"id":324,
"foo":1,
"event":"ABC 3166-1_2013 No. VII-11",
"date":"2018-06-30T00:00:00.000Z",
},
{
"id":326,
"foo":2,
"event":"ABC 3166-1_2016 No. VII-12",
"date":"2018-06-30T00:00:00.000Z",
}
]
My use case for this is so I can provide a filtered set of options for an HTML drop down select input.
Does anyone have any idea on how I can satisfy my use case and get a filtered set of items in a new array?
>Solution :
You could use filter function of the array and includes method of strings :
let arr=[{
"id":332,
"foo":6,
"event":"ABC-CNEG Correlations Ed3.0 Update 9 (XY-AHZ)",
"date":"2018-11-26T00:00:00.000Z",
},
{
"id":324,
"foo":1,
"event":"ABC 3166-1_2013 No. VII-11",
"date":"2018-06-30T00:00:00.000Z",
},
{
"id":325,
"foo":1,
"event":"ABC 3166-2_2013 To. XII-32",
"date":"2018-06-30T00:00:00.000Z",
},
{
"id":326,
"foo":2,
"event":"ABC 3166-1_2016 No. VII-12",
"date":"2018-06-30T00:00:00.000Z",
},
{
"id":327,
"foo":1,
"event":"ABC 3166-2_2018 To. XII-31",
"date":"2018-06-30T00:00:00.000Z",
}]
let result=arr.filter(item=>item.event.includes('3166-1'))
console.table(result)