Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I ceate new array of elements based on a pattern found in another array?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading