Reputation: 3
The function below will log the value of newData
but returns undefined
when called. Does anyone know why this might be? Also, any feedback on the function itself would be greatly appreciated!
export const filterByDateTimeRange = (data=[{}], timeKey=[], startTime=moment(), stopTime=moment()) => {
let newData = [];
let i = 0;
for(const item of data) {
let time;
let index = 0
timeKey.map(key => {
time ? time = time[key] : time = item[key];
index++
if(index === timeKey.length) {
if(moment(time).isBetween(startTime, stopTime, undefined, '[)')) {
newData.push(item)
};
i++;
if(i === data.length) {
console.log(newData);
return (newData);
}
}
})
}
}
Upvotes: 0
Views: 46
Reputation: 4050
The map
function is usually used to transform a collection and store the results, for example:
var squares = [2, 3, 4].map(x => { return x * x });
// result is squares = [4, 9, 16]
The forEach
function is more appropriate to use here since you just want to loop over the array and don't care about storing a transformation.
Then when the outer loop finishes your function can return newData
export const filterByDateTimeRange = (data=[{}], timeKey=[], startTime=moment(), stopTime=moment()) => {
let newData = [];
let i = 0;
for(const item of data) {
let time;
let index = 0
timeKey.forEach(key => { //changed to a forEach loop
time ? time = time[key] : time = item[key];
index++
if(index === timeKey.length) {
if(moment(time).isBetween(startTime, stopTime, undefined, '[)')) {
newData.push(item)
};
i++;
if(i === data.length) {
console.log(newData);
}
}
});
}
return newData; //add the return after your loop finishes
}
Upvotes: 2
Reputation: 1
This return inside a map function. Not return of filterByDateTimeRange(). If you want to return newData. Replace map function by for loop.
Map: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Upvotes: 0