Javascript数组提取重复到新数组

时间:2014-05-13 15:48:11

标签: javascript arrays

我有以下数组:

optionsList = [{"id":73,"option_id":19,"label":"1GB DDR2 RAM (default)","sort_order":0,"value":"1GB DDR2 RAM (default)"},{"id":74,"option_id":19,"label":"2GB DDR2 RAM (+ $15.00)","sort_order":1,"value":"2GB DDR2 RAM (+ $15.00)"},{"id":75,"option_id":20,"label":"No (Default)","sort_order":0,"value":"No (Default)"},{"id":76,"option_id":20,"label":"Yes (+$18)","sort_order":1,"value":"Yes (+$18)"},{"id":77,"option_id":21,"label":"19\" Monitor ","sort_order":0,"value":"19\" Monitor "},{"id":78,"option_id":21,"label":"20\" Monitor (+ $10.00)","sort_order":1,"value":"20\" Monitor (+ $10.00)"},{"id":79,"option_id":21,"label":"22\" Monitor (+ $20.00)","sort_order":2,"value":"22\" Monitor (+ $20.00)"},{"id":80,"option_id":22,"label":"Window XP Pro","sort_order":0,"value":"Window XP Pro"},{"id":81,"option_id":22,"label":"Windows Vista","sort_order":1,"value":"Windows Vista"},{"id":82,"option_id":22,"label":"Windows 7 Professional (+$55.00)","sort_order":2,"value":"Windows 7 Professional (+$55.00)"},{"id":83,"option_id":23,"label":"No Antivirus","sort_order":0,"value":"No Antivirus"},{"id":84,"option_id":23,"label":"Norton Anitivirus","sort_order":1,"value":"Norton Anitivirus"},{"id":85,"option_id":23,"label":"Macafee Antivirus","sort_order":2,"value":"Macafee Antivirus"}]

我需要遍历并为每个重复的option_id值创建一个新数组。

所以新数组看起来像:

第一行

{'label':'1GB DDR2 Ram (Default)'},
{'id':73,'label':'1GB DDR2 Ram (+$15)':'id:74}

第二行

{'label':'No (Default)',
'id':75},{'label':'Yes (+$15)':'id:76}

MrWarby

我尝试了以下内容:

    var sortedOptionsList = sortArray(optionsList);
    var sorted_arr = optionsList.sort(); 
    //alert(app.OBJ2JSON(sorted_arr)) ;                    
    var results = [];
    for (var i = 0; i < optionsList.length - 1; i++) {
        if (sorted_arr[i + 1]['option_id'] == sorted_arr[i]['option_id']) {
    results.push(sorted_arr[i]);

function sortArray(array){
        array.sort(function (element_a, element_b) {
    return element_a[1] - element_b[1];
        });     
}

但是排序的数组没有按元素option_id排序。

1 个答案:

答案 0 :(得分:-2)

我解决这个问题的方法是遍历数组,通过测试数组上的indexOf来获取副本的密钥,然后在找到匹配项时删除密钥。