问题描述
假设我们有一个像
数组 VAR一个= [
{名称:'汤姆',姓:TestAsIvanov},
{名称:'凯特',姓:诺娃},
{名称:'约翰',姓:Alivanov},
{名称:'伊万',姓:伊万诺夫}
]
我需要排序这个数组通过基于提供的字符串,例如姓字段:
- 为
IVA
模板阵列应排序如下:
VAR纽瓦= [
{名称:'伊万',姓:伊万诺夫},
{名称:'凯特',姓:诺娃},
{名称:'约翰',姓:Alivanov},
{名称:'汤姆',姓:TestAsIvanov},
]
'A'
模板阵列应按照如下顺序排列 VAR纽瓦= [
{名称:'约翰',姓:Alivanov},
{名称:'伊万',姓:伊万诺夫},
{名称:'凯特',姓:诺娃},
{名称:'汤姆',姓:TestAsIvanov},
]
因此,阵列应该由提供的字符串的模式有序。这怎么可能实现呢?
我做了一个简单的排序脚本的。我不知道这是否是最好的方法,因为我不得不用两个排序()
方法,一是按字母顺序排序(的拍摄)和另一模拟 LIKE'字符串%'
(比较SQL),让您的病情
VAR的queryString =IVA;一个= a.sort(功能(A,B){
变种S1 = a.surname.toUpperCase()的indexOf(queryString.toUpperCase())。
变种S2 = b.surname.toUpperCase()的indexOf(queryString.toUpperCase())。 回报(S1 -1个和放大器;&安培; S1> S2);
});
至少它与你提供的这两个例子中的工作,但我不知道这是否是你所需要的。
Suppose we have an array like
var a = [
{ name: 'Tom', surname: 'TestAsIvanov' },
{ name: 'Kate', surname: 'Ivanova' },
{ name: 'John', surname: 'Alivanov' },
{ name: 'Ivan', surname: 'Ivanov' }
]
I need to sort this array by surname field based on a provided string, e.g.:
- for
'iva'
the pattern array should be sorted as follows
var newA = [
{ name: 'Ivan', surname: 'Ivanov' },
{ name: 'Kate', surname: 'Ivanova' },
{ name: 'John', surname: 'Alivanov' },
{ name: 'Tom', surname: 'TestAsIvanov' },
]
- for
'a'
the pattern array should be sorted as follows
var newA = [
{ name: 'John', surname: 'Alivanov' },
{ name: 'Ivan', surname: 'Ivanov' },
{ name: 'Kate', surname: 'Ivanova' },
{ name: 'Tom', surname: 'TestAsIvanov' },
]
So arrays should be ordered by string pattern provided. How is it possible to implement this?
I've made a simple sort script for that. I don't know if it is the best way because I had to use two sort()
methods, one to sort alphabetically(taken from here) and another to simulate a LIKE 'string%'
(comparing to SQL) to get your condition:
var queryString = "iva";
a = a.sort(function(a, b) {
var s1 = a.surname.toUpperCase().indexOf(queryString.toUpperCase());
var s2 = b.surname.toUpperCase().indexOf(queryString.toUpperCase());
return (s1 > -1 && s1 > s2);
});
At least it worked with both examples you provided, but I'm not sure if it is all you need.
这篇关于基于字符串对象的数组排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!