I have successfully created a new array containing only unique values, but I am facing issues with my count function. The desired result is to display the number of items in the array for each color.
The expected outcome would be:
4 red
10 blue
1 green
Currently, the result shows a count of 0 for each color. I suspect this may be due to me adding the count property while mapping the array to a new variable.
I used the if (loopComplete == false)
condition because I was encountering undefined errors and wanted to ensure that the second for
loop runs after the first one completes.
var vm = new Vue({
el: '#app',
data: {
myArray: [
{ color: 'red',
number: '1'
},
{
color: 'red',
number: '2'
},
// other array elements...
],
},
computed: {
filteredArray() {
return this.count(this.myArray);
}
},
methods: {
count(array) {
let newArray = array.map(function(item) {
return {
'color': item.color,
'count': 0,
};
});
let arrayUnique = [];
let arrayAdded = [];
let loopComplete = false;
if (loopComplete == false) {
for (let i = 0; i < newArray.length; i++) {
if (!arrayAdded.includes(newArray[i].color)) {
arrayAdded.push(newArray[i].color);
arrayUnique.push(newArray[i]);
}
}
loopComplete = true;
return arrayUnique;
} else {
for (let i = 0; i < newArray.length; i++) {
if (arrayUnique.includes(newArray[i].color)) {
arrayUnique[i].count++;
}
return arrayUnique;
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div v-for="result in filteredArray">
{{ result.count }} {{ result.color }}
</div>
</div>