Last active
December 20, 2022 07:55
-
-
Save jtulk/4c7b379dd13a2a9906efe8ca2cf81603 to your computer and use it in GitHub Desktop.
Merge, Dedupe, and Update Arrays in a Redux Reducer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const ADD_PROJECTS = "projects/add_projects" | |
const initialState = { | |
projects: [] | |
} | |
function reducer(state = initialState, action = {}){ | |
switch(action.type){ | |
case ADD_PROJECTS: | |
// Add a timestamp for the new projects | |
const timeStamp = new Date().getTime() | |
const stampedActionProjects = action.projects.map((proj) => { | |
proj.timeStamp = timeStamp | |
return proj | |
}) | |
// combine the old projects with the new timeStamped ones | |
// then sort by ID value | |
const combinedArrays = [...state.projects, ...stampedActionProjects].sort((a, b) => { | |
return a.id > b.id | |
}) | |
const finalArray = combinedArrays.reduce((prev, cur, index, array) => { | |
// This is the value that we'll return at the end of each reduce iteration | |
let toReturn | |
// Get a reference to the last item in the PREV array | |
const lastObj = prev[prev.length - 1] | |
// if the IDs are different, concat the cur obj into the prev array | |
if(lastObj.id !== cur.id){ | |
toReturn = prev.concat(cur) | |
} | |
// if the IDS are different, compare the timestamp values | |
// store the most recent timestamp in the PREV array | |
else if (lastObj.timeStamp < cur.timeStamp){ | |
prev.splice((prev.length - 1), 1, cur) | |
toReturn = prev | |
} | |
// otherwise just return the previous value | |
else { | |
toReturn = prev | |
} | |
return toReturn | |
}, [combinedArrays[0]]) | |
return { | |
projects: finalArray | |
} | |
default: | |
return state | |
} | |
} | |
function addProjects(projects){ | |
return { | |
type: ADD_PROJECTS, | |
projects: projects | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment