What is a efficient method to iterate through a JavaScript array of objects, and within each object, verify the uniqueness of a specific value compared to all others before adding it to a new array.
Here is the sample array of objects:
const weatherArray = [
{
dt: 1526871600
dt_txt: "2018-05-21 03:22:00"
},
{
dt: 1526871600
dt_txt: "2018-05-22 03:30:00"
},
{
dt: 1526871600
dt_txt: "2018-05-21 03:50:00"
},
{
dt: 1526871600
dt_txt: "2018-05-23 03:17:00"
},
{
dt: 1526871600
dt_txt: "2018-05-23 03:23:00"
}
]
The goal is to examine each object and only add those with unique dt_txt values (date portion only, excluding time) to a new array.
Attempted solution provided below with annotations:
var uniqueDays = []
function getDays(weatherArray) {
// Add the first value to new array for comparison
uniqueDays.push(weatherArray[0])
// Extract date portion from dt_txt for comparison
let firstDayString = weatherArray[0].dt_txt.split(" ")[0]
weatherArray.map((day) => {
let dayString = day.dt_txt.split(" ")[0]
uniqueDays.map((uniqueDay, index) => {
// Extract date portion from new array items
let unqiueDayString = uniqueDay.dt_txt.split(" ")[0]
// Skip if the value already exists
if (unqiueDayString == dayString) {
console.log('duplicate');
} else {
// Otherwise add to new array (issue identified)
uniqueDays.push(day)
}
})
})
return uniqueDays
}
The recursion issue arises from pushing within the same map function. Seeking advice on better strategies or solutions for this problem. Any suggestions would be greatly appreciated as I've been grappling with this challenge for some time.