When receiving an array of objects through an API call in my Vuejs front-end application, I faced the task of looping through the data to eliminate duplicates and create a new array containing unique "phases" along with their respective "id's". The original array contained unnecessary key-value pairs, so I needed to filter them out. Additionally, I wanted the phases to be sorted in ascending order based on their phase numbers. Below is the code I used:
salesPhases () {
let phases = this.$store.state.addresses.salesPhases
let uniquePhases = []
for (let i = 0; i < phases.length; i++) {
if (uniquePhases.indexOf(phases[i].phase_number) === -1) {
uniquePhases.push(phases[i].phase_number)
}
}
return uniquePhases.sort((a, b) => {
return a - b
})
}
The code snippet above successfully achieved what I needed, except for including the id
along with the phases. My attempt to include it resulted in losing the uniqueness condition as follows:
uniquePhases.push([phases[i].phase_number, phases[i].id])
Even though the sorting function continues to work, it now sorts a single-dimensional array that combines both phases and ids. An example snippet of the phases array structure is shown below:
{ "data": [
{
"id": "94e224af-135f-af31-3619-535acfae9930",
"street_address1": "407 48TH ST E",
"street_address2": null,
"phase": "101",
"sales_rep": "164",
"id": "abd90d6b-28a8-2be6-d6c1-abd9007aef38",
"name": "48TH ST E",
"block_minimum": 400,
"block_maximum": 498,
"side": 2
},
{
"id": "94e224af-135f-af31-3619-535acfae9930",
"street_address1": "407 48TH ST E",
"street_address2": null,
"phase": "101",
"sales_rep": "164",
"id": "abd90d6b-28a8-2be6-d6c1-abd9007aef38",
"name": "48TH ST E",
"block_minimum": 401,
"block_maximum": 499,
"side": 1
}
]