Help needed with filtering an array:
In the user_array, there are arrays that need to be compared to see if the header_info.sap_number
matches any value in the valid_sap_number array
.
If a property value matches anything in the valid_sap_number array
, the array and its parent array will be retained, while all other arrays that do not match any value from the valid_sap_number array
will be removed. Refer to the example below for clarification.
Example array:
var valid_sap_number = ['1', '2']
var user_array =
[{
"name": "User1",
"header_info": [{ "sap_number": "1" }],
"footer_info": [{ "site": "ABC" }]
}],
[{
"name": "User2",
"header_info": [{ "sap_number": "2" }],
"footer_info": [{ "site": "ABCD" }]
}],
[{
"name": "User3",
"header_info": [{ "sap_number": "3" }],
"footer_info": [{ "site": "ABC" }]
}];
/* Filter code */
const result = user_array.filter(user => function(a,b){
for(i = 0; i < valid_sap_number.length; i++)
{
if(b.header_info[0].sap_number == valid_sap_number[i]){
return true;
}
}
});
console.log(result);
Expected output:
result = [{
"name": "User1",
"header_info": [{ "sap_number": "1" }],
"footer_info": [{ "site": "ABC" }]
}],
[{
"name": "User2",
"header_info": [{ "sap_number": "2" }],
"footer_info": [{ "site": "ABCD" }]
}];