JS the array of objects sorted according to an attribute of an object

1. An array of objects

We now have a set of objects, include "name, value" attributes, to achieve these objects be sorted according to value.

Series: [ 
{name: 'Xi'an', value: 100},
{name: 'Shenyang K', value: 120},
{name: 'Yan'an City', value: 80},
{name: 'Dunlop City ', value: 90},
{name:' Yulin ', value: 130.}
]

2. The sorting method

Actually that sort method of array objects.

Array.sort(fun)

fun is a function, sorting is performed based on this function return value is determined, if the return value is less than 0 indicates two elements without exchanging position, a position 1 represents interactive use, equal to 0 indicates, in fact <= 0 is equivalent.

There are two sort Precautions:

  1. It will operate the original array, after the operation changes the original array
  2. The default sort sort by character encoding, for example, we have one of the following examples:
of arr1 = var [14,23,11,6,87,67]; 
arr1.sort (); // [11,14,23,6,67,87] Sort by numerical characters instead of

Want to accomplish value comparison sort must pass sort parameters (function) to regulate the development of:

sortRule function (A, B) { 
  return ab &; // if a> = b, returns a natural number, do not change position 
} 
arr1.sort (sortRule);

However, if you encounter each element is not a value, but the object, it should be how to deal with it? Actually, it is the same, but we have to rewrite a fit subject of regulation in the regulation function:

functon sortRule(a,b) {
    return a.value- b.value;
}

Of course, write only the object's value property, which we know to be sorted in a clear case of an array of objects, if the object array element value property does not exist, it would be an error, and therefore, you write your own rules , judge rules should apply to other property.

If we do not specify which properties sorted by, for example, in addition to value property, we have other properties, hoping to repeat with this algorithm, how should we do it?

function sortBy(props) {
    return function(a,b) {
        return a[props] - b[props];
    }
}
arr1.sort(sortBy("value"));

Yes, the core code so simple. In following this idea, we can do an idea: If the value is equal under the circumstances, if we can sort the size of the output of other attributes?

function sortBy(field1,field2) {
    return function(a,b) {
        if(a.field1 == b.field1) return a.field2 - b.field2;
        return a.field1 - b.field1;
    }
}
arr1.sort(sortBy("value","score"));

Yes, it's that simple fact, you can even use argments to get more parameters to pass more fields as the judgment condition.

 

 

 

 

Original Reference: https://www.tangshuang.net/2406.html

 


Guess you like

Origin www.cnblogs.com/iamlhr/p/11459653.html