I was writing some code and something puzzled me. I have an array of numbers called alarmsList
. Now I wish to iterate through this list and if a value is higher than 60 for example I want to create a new object array (collection) where we store the high value and it's index from the original array. So take the following code
const alarmsList = [1, 61, 77, 4, 5, 6, 7, 8, 85, 4, 3, 55];
const highAlarmsList = alarmsList.map((item, index) => {
if(item > 60) {
return ({ value: item, index })
}
});
console.log(highAlarmsList)
The console.log outputs the following
[
undefined,
{
"value": 61,
"index": 1
},
{
"value": 77,
"index": 2
},
undefined,
undefined,
undefined,
undefined,
undefined,
{
"value": 85,
"index": 8
},
undefined,
undefined,
undefined
]
This output is what I require but how do I prevent the undefined values being returned? I thought about using array.filter but that doesn't seem appropriate? Should I use a different array method? I don't want to use a for loop and push to a new array unless that is the best/only way to achieve the new array without the undefined values being returned.