I have some default steps which my order goes through
const defaultSteps = [
'In preparation',
'Order taken from courier',
'Order is on its way',
'Order delivered to customer',
'Partner declined order'
];
I get from backend history array which contains date when status is changed and name of status
history: [ { status_name: "In preparation", status_id: "62a74ac2fc767ef024f031cd", date_updated: 2022-06-14T20:29:51.784+00:00 }, { status_name: "Order taken from courier", status_id: "62a74ac2fc767ef024f031cd", date_updated: 2022-06-14T20:29:51.784+00:00 } ]
I want to create new array that checks if that step is in history, push that element from history with date field to array else push's element from defaultSteps
If I understand your question, you can loop through both arrays with Array.forEach() and push the elements into the new array:
const defaultSteps = [
'In preparation',
'Order taken from courier',
'Order is on its way',
'Order delivered to customer',
'Partner declined order'
];
const result = []
const history = [ { status_name: "In preparation", status_id: "62a74ac2fc767ef024f031cd", date_updated: "2022-06-14T20:29:51.784+00:00" }, { status_name: "Order taken from courier", status_id: "62a74ac2fc767ef024f031cd", date_updated: "2022-06-14T20:29:51.784+00:00" } ]
defaultSteps.forEach(str => {
let hasMatch = false
history.forEach(obj => {
if(str === obj.status_name) {
result.push(obj)
hasMatch = true
}
})
if(!hasMatch) {
result.push(str)
}
})
console.log(result)
If I understand the question correctly you can do this:
const data = defaultSteps.map(item => history.find(i => i.status_name === item) || item)
data is your new array