Search
Learn
Share

Vue.js: Sorting array on a custom filter - Avoid an infinite loop

Published by Profile Image LGK on 6 December, 2016
419 views
With Vue.js you can create custom filters as a method like this:

index.html
<main id="app">
<div v-for="i in even(items)" class="item">
{{i.title}}
<small>{{i.position}}</small>
</div>
</main>

main.js
var app = new Vue({
el: "#app",
data: {
items: [
{
"title": "Jerry",
"position": 5
},
{
"title": "Bucks Bunny",
"position": 1
}
]
},
methods: {
even: function(arr) {
return arr.sort(function(a, b) {
return a.position - b.position;
});
}
}
});

STOP, DON'T USE THAT CODE!
arr.sort(...) will generate an infinite loop. To avoid that, you should use slice() before the sort() function. Like this:

main.js
var app = new Vue({
el: "#app",
data: {
items: [
{
"title": "Jerry",
"position": 5
},
{
"title": "Bucks Bunny",
"position": 1
}
]
},
methods: {
even: function(arr) {
// Set slice() to avoid to generate an infinite loop!
return arr.slice().sort(function(a, b) {
return a.position - b.position;
});
}
}
});

You can find a live demo on CodePen: http://codepen.io/lgkonline/pen/dOebrw