【问题标题】:Javascript array extract duplicates into new arrayJavascript数组将重复项提取到新数组中
【发布时间】:2014-07-01 09:37:57
【问题描述】:

我有以下数组:

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}

沃比先生

我尝试了以下方法:

    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 排序的。

【问题讨论】:

  • 如果您在一天内遇到问题,请继续并在此处发布
  • 本网站的重点是不要让学生放弃他们的家庭作业让其他人完成...如果您对自己编写的代码有具体问题,我们很乐意为您提供帮助.
  • 已使用经过验证的代码更新

标签: javascript arrays


【解决方案1】:

我解决这个问题的方法是遍历数组,并通过测试数组上的 indexOf 来获取副本的键,如果找到匹配项则删除该键。

【讨论】:

    猜你喜欢
    • 2013-03-21
    • 1970-01-01
    • 1970-01-01
    • 2018-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-03
    • 2020-06-01
    相关资源
    最近更新 更多