将对象数组排序为字符串?

时间:2014-09-05 09:20:28

标签: javascript

我想在数组中找到重复的对象。我想通过对数组进行排序然后将项目相互比较来做到这一点。如何将对象"作为字符串进行比较"这意味着如果有任何差异,他们会相应地进行排序吗?

它是我想要替换的排序功能。

    var newCart = shoppingCart.sort();

    var results = [];
    for (var i = 0; i < newCart.length - 1; i++) {
        if (newCart[i + 1] == newCart[i]) {
            results.push(newCart[i]);
        }
    }

    this.products = results;

示例输入:

[
    {
        "id": 1,
        "name": "Skateboard",
        "price": 1299,
        "currency": "SEK",
        "thumbnail": "/static/img/products/1-t.jpg"
    },

    {
        "id": 4,
        "name": "A trip to the sun with Erik",
        "price": 29000,
        "currency": "SEK",
        "thumbnail": "/static/img/products/4-t.jpg"
    },

    {
        "id": 1,
        "name": "Skateboard",
        "price": 1299,
        "currency": "SEK",
        "thumbnail": "/static/img/products/1-t.jpg"
    },

    {
        "id": 4,
        "name": "A trip to the sun with Erik",
        "price": 29100,
        "currency": "SEK",
        "thumbnail": "/static/img/products/4-t.jpg"
    },
    {
        "id": 4,
        "name": "A trip to the sun with Erik",
        "price": 29000,
        "currency": "SEK",
        "thumbnail": "/static/img/products/4-t.jpg"
    },
]

示例输出:

[
    {
        "id": 1,
        "name": "Skateboard",
        "price": 1299,
        "currency": "SEK",
        "thumbnail": "/static/img/products/1-t.jpg"
    },
    {
        "id": 1,
        "name": "Skateboard",
        "price": 1299,
        "currency": "SEK",
        "thumbnail": "/static/img/products/1-t.jpg"
    },

    {
        "id": 4,
        "name": "A trip to the sun with Erik",
        "price": 29000,
        "currency": "SEK",
        "thumbnail": "/static/img/products/4-t.jpg"
    },

    {
        "id": 4,
        "name": "A trip to the sun with Erik",
        "price": 29000,
        "currency": "SEK",
        "thumbnail": "/static/img/products/4-t.jpg"
    },
        {
        "id": 4,
        "name": "A trip to the sun with Erik",
        "price": 29100,
        "currency": "SEK",
        "thumbnail": "/static/img/products/4-t.jpg"
    },
]

请注意,输出中的最后一项最后结束,因为价格与具有相同ID的其他项目的价格不同。

2 个答案:

答案 0 :(得分:0)

您可以使用JSON.stringify

    function sort(arr) {
        if (arr.length == 0) return [];
        var result = [];
        var v = arr[0];
        result.push(v);
        arr.splice(0,1);;
        for (var i = 0; i < arr.length - 1; i++) {
            if (JSON.stringify(arr[i]) == JSON.stringify(v)) {
                result.push(arr[i]);
                arr.splice(i,1);
            }
        }
            return result.concat(sort(arr));
    }

console.log(JSON.stringify(sort(arr)));

DEMO

答案 1 :(得分:0)

我已经完成了这个简单的JavaScript 排序方法:

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

Solution