[英]AngularJS or Javascript: Sort array(ASC & DESC) using index only
Assume i have a javascript object, like so: 假设我有一个javascript对象,如下所示:
var arrObject = [
{id:'01', name:'John'},
{id:'02', name:'Joseph'},
{id:'03', name:'Tom'},
{id:'04', name:'Nick'}
];
I have to sort the object in DESC order by index only. 我只能按索引按DESC顺序对对象进行排序。 To sort, should not use any key from the object.
进行排序时,不应使用对象中的任何键。 Result:
结果:
var arrObject = [
{id:'04', name:'Nick'},
{id:'03', name:'Tom'},
{id:'02', name:'Joseph'},// to be remove
{id:'01', name:'John'},
];
Suppose I have deleted third item ie id = '02', and added new item object. 假设我删除了第三个项目,即id ='02',并添加了新的项目对象。 Now, Object looks:
现在,对象看起来:
var arrObject = [
{id:'05', name:'Harrison'}, //new added item
{id:'04', name:'Nick'},
{id:'03', name:'Tom'},
{id:'01', name:'John'}
];
So, whenever I perform Add/Delete operation on the object I have to sort the array in DESC order by index only. 因此,每当我对对象执行添加/删除操作时,都必须仅按索引按DESC顺序对数组进行排序。 That way I can keep the new item on top always and so on.
这样,我就可以始终将新项目放在首位,依此类推。
Note : No need to put the additional key in the object for sort purpose, as items from the object can be removed or added. 注意 :无需出于排序目的将附加键放在对象中,因为可以删除或添加对象中的项。
I do not see any built-in method would work for this directly, if yes that would great. 我看不到有任何内置方法可以直接用于此,如果可以的话,那会很棒。 If not, how would you go about writing a method that does this?
如果没有,您将如何编写一个执行此操作的方法? Any help would be appreciated !!
任何帮助,将不胜感激 !!
Solution preferred in AngularJS, but Javascript also welcomed. 在AngularJS中首选解决方案,但也欢迎使用Javascript。
First - arrObject is an array of objects - this allows an index in the first place. 首先-arrObject是对象数组-首先允许索引。
This issue seems to be a js only issue - simply use unshift()
to add new items to the start of the array 这个问题似乎只是一个JS问题-只需使用
unshift()
将新项目添加到数组的开头
var arrObject = [ {id:'05', name:'Harrison'}, {id:'04', name:'Nick'}, {id:'03', name:'Tom'}, {id:'01', name:'John'} ]; arrObject.unshift({id:'06', name:'Gavin'}); console.log(arrObject); // puts the newly added Gavin object ar ethe start of the array.
but if you really want to push
an item to the end of the array then - .reverse() would seem to be what you want - ie array.reverse()
will present the array from the end to the start 但是,如果您真的想
push
项目push
到数组的末尾,那么-.reverse()似乎就是您想要的-即array.reverse()
将从末尾开始显示数组
var arrObject = [ {id:'01', name:'John'}, {id:'03', name:'Tom'}, {id:'04', name:'Nick'}, {id:'05', name:'Harrison'}, ]; arrObject.push({id:'06', name:'Gavin'});// puts the Gavin object ar ethe end of the array. console.log(arrObject.reverse()); // renders the array in reverse orderwith the Gavin object shown first
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.