多维数组排序

时间:2012-03-09 23:49:49

标签: javascript arrays sorting

我在javascript中有一个多维数组定义为: -

myArray[0][0] = Some IMage;
myArray[0][1] = Some price;
myArray[0][2] = Some name;
myArray[0][3] = Some values;
myArray[0][4] = Some otherValues;
myArray[1][0] = Some IMage;
myArray[1][1] = Some price;
myArray[1][2] = Some name;
myArray[1][3] = Some values;
myArray[1][4] = Some otherValues;

现在我的工作是根据价格对它们进行分类。怎么办呢?

5 个答案:

答案 0 :(得分:5)

根据我上面的评论,您应该使用对象而不是多维数组。这是一个示例(想象一下您的其他属性,例如nameIMage,我为了减少打字而没有包含这些属性)

var arr = [
    { price: 12, something: 'a b c' },
    { price: 8, something: 'a b c' },
    { price: 45, something: 'a b c' },
    { price: 10, something: 'a b c' }
];

arr.sort(function(a, b) { return a.price - b.price; });

/*
    arr is now:

    [ 
        { price: 8, something: 'a b c' },
        { price: 10, something: 'a b c' },
        { price: 12, something: 'a b c' },
        { price: 45, something: 'a b c' } 
    ]
*/

答案 1 :(得分:2)

如果有人搜索问题,这里是没有判断数据结构的答案。有时需要这样的“不正确”结构(例如:作为dataTables的输入)。

arr.sort(function(a, b) { return a[1] - b[1]; });

答案 2 :(得分:1)

数组有一个sort函数,它接受另一个函数作为比较器。您可以按如下方式对数据进行排序:

var comparator= function(a,b){
   var price1 = a[1], price2=b[1]; // use parseInt() if your "price" are quoted 
   if( price1 < price2) return -1;
   else return 1;
   return 0;
};
myArray.sort(comparator);

答案 3 :(得分:1)

从马歇尔借来。

var myArray = [];
myArray.push({
    image: 'some image',
    price: 1.5,
    name: 'name',
    values: 'values',
    otherValues: 'otherValues'
});

myArray.push({
    image: 'some image2',
    price: 0.5,
    name: 'name2',
    values: 'values2',
    otherValues: 'otherValues2'
});

myArray.push({
    image: 'some image3',
    price: 2.5,
    name: 'name3',
    values: 'values3',
    otherValues: 'otherValues3'
});

myArray.sort(function (a, b) {
    return a.price - b.price;
});

alert(myArray[0].price);
alert(myArray[1].price);
alert(myArray[2].price);

答案 4 :(得分:0)

Javascript多标准/多参数排序

如果要按单个值或多个值对数组进行排序,可以定义以下函数:

function sortByCriteria(data, criteria) {
    return data.sort(function (a, b) {

        var i, iLen, aChain, bChain;

        i = 0;
        iLen = criteria.length;
        for (i; i < iLen; i++) {        
            aChain += a[criteria[i]];
            bChain += b[criteria[i]];
        }

        return aChain.localeCompare(bChain);
    });
}

然后像这样调用:

var data = [
    { price: 12, something: 'a b c' },
    { price: 8, something: 'a b c' },
    { price: 45, something: 'a b c' },
    { price: 10, something: 'a b c' }
];
var criteria = ["price", "something"];

sortByCriteria(data, criteria);

http://jsfiddle.net/oahxg4u3/6/