0

I have two array as follows :

data = [
{
 "is_new":1,
 "is_delayed":0,
 "is_active":1,
 "name":"london"
},
{
 "is_new":1,
 "is_delayed":1,
 "is_active":0,
 "name":"paris"
},
{
 "is_new":1,
 "is_delayed":0,
 "is_active":1,
 "name":"India"
}
]

secondArray = ["is_new","is_delayed","is_active"] -- this array can have one element, two element or three elements at runtime

I want to filter data array such that whatever values matches in second array should have value 1 in that element of data array. For example in second array if three elements i.e "is_new","is_delayed","is_active" are present, then I want to check for first element in data array for any of these value is 1, then add that element in a result array. How can I do that?

Rosy
  • 71
  • 4
  • yes it should be included – Rosy Mar 30 '23 at 06:49
  • Quite a large part of your problem involves finding the “nth item in an object”: https://stackoverflow.com/questions/35722324/how-to-select-nth-item-inside-the-object it should be quite straightforward to get what you want from this point. – Joachim Mar 30 '23 at 06:50
  • @Rosy are you looking for something like this – cmgchess Mar 30 '23 at 09:23

1 Answers1

2

a filter and some should do. some gives true if at least 1 element satisifies the condition. here the condition is if the field is 1 (achieved by the e[f] === 1 or simply e[f])

const data = [
{
 "is_new":1,
 "is_delayed":0,
 "is_active":1,
 "name":"london"
},
{
 "is_new":1,
 "is_delayed":1,
 "is_active":0,
 "name":"paris"
},
{
 "is_new":1,
 "is_delayed":0,
 "is_active":1,
 "name":"India"
}
]

const secondArray = ["is_new","is_delayed","is_active"]

const res = data.filter(e => secondArray.some(f => e[f]))

console.log(res)

if by any case you need to satisfy all given in the secondArray to be 1 then you can use every. It gives true only if every element satisfies the condition

const data = [
{
 "is_new":1,
 "is_delayed":0,
 "is_active":1,
 "name":"london"
},
{
 "is_new":1,
 "is_delayed":1,
 "is_active":0,
 "name":"paris"
},
{
 "is_new":1,
 "is_delayed":0,
 "is_active":1,
 "name":"India"
}
]

const secondArray = ["is_new","is_delayed"]

const res = data.filter(e => secondArray.every(f => e[f]))

console.log(res)
cmgchess
  • 7,996
  • 37
  • 44
  • 62