0

オブジェクト/配列のアイテムを「名前」アイテムでソートしようとしていますが、

このページを参照用に使用して、オブジェクトの配列をソートし、以下のコードをビルドします。

var alphabet = {
    a: 1,
    b: 2,
    c: 3,
    d: 4,
    e: 5,
    f: 6,
    g: 7,
    h: 8,
    i: 9,
    j: 10,
    k: 11,
    l: 12,
    m: 13,
    n: 14,
    o: 15,
    p: 16,
    q: 17,
    r: 18,
    s: 19,
    t: 20,
    u: 21,
    v: 22,
    w: 23,
    x: 24,
    y: 25,
    z: 26
}

var test = {
    item: {
        name: "Name here",
        email: "example@example.com"
    },

    item2: {
        name: "Another name",
        email: "test@test.com"
    },

    item3: {
        name: "B name",
        email: "test@example.com"
    },

    item4: {
        name: "Z name",
        email: "example@text.com"
    }
};
test.sort(function (a, b) {return alphabet[a.name.charAt(0)] - alphabet[b.name.charAt(0)]});

console.log(test);

残念ながら、エラーは返されず、console.log も何も返されません。どんな助けでも大歓迎です!

編集: 答えが与えられた後、変数「test」は配列である必要があるように見えましたが、変数は外部ライブラリで動的に生成されたため、この小さなコードを作成しました。同じように悩んでいる人がいたら、ぜひ使ってみてください。

var temp = [];
$.each(test, function(index, value){
    temp.push(this);
});

//temp is the resulting array
4

2 に答える 2

4

test配列ではなくオブジェクトです。おそらくあなたはこれが欲しい:

var test = [
    {
        name: "Name here",
        email: "example@example.com"
    },
    ⋮
];

item, , … を各オブジェクトに対して保持する必要がある場合はitem1、それらを各オブジェクトのフィールドとして追加できます。

var test = [
    {
        id: "item",
        name: "Name here",
        email: "example@example.com"
    },
    ⋮
];

アルファベット順に並べ替えるには、大文字と小文字を区別しないコンパレータが必要です (alphabetオブジェクトを無視します)。

compareAlpha = function(a, b) {
  a = a.name.toUpperCase(); b = b.name.toUpperCase();
  return a < b ? -1 : a > b ? 1 : 0;
};
于 2012-04-15T23:37:37.470 に答える
1

まず、test はオブジェクトではなく配列である必要があります。第二に、文字を選択した後に .toLowerCase() への呼び出しが欠落していると思います。

test.sort(function (a, b) {
    return alphabet[a.name.charAt(0).toLowerCase()] - alphabet[b.name.charAt(0).toLowerCase()];
});
于 2012-04-15T23:38:12.037 に答える