创建一个新的数组,一起添加重复的值

时间:2015-05-11 22:42:48

标签: javascript arrays duplicates

我有一个二维数组:

[[bourbon, 2], [bourbon, 1],[scotch, 2]]

我想最终得到一个新的数组来整合重复项,以便数组成为

 [[bourbon, 3], [scotch, 2]]

以下是我创建数组的方法:

    for(var i=0; i< data.length; i++){
         var typeW = String(data[i].doc.type);
         var valueAsNumber = parseInt(data[i].doc.bottle);
         typeOfWhiskey[j,i] = [typeW,valueAsNumber];
         j++;
    }   

我尝试使用if(typeOfWhiskey.indexOf(typeW ) > -1){

检查唯一值

但是我目前卡住了。在这个例子中,&#39; typeW&#39;是&#39; bourbon&#39;或&#39; scotch&#39;的字符串值。例如,作为&#39; valueAsNumber&#39;根据提供的示例,它将是2或1。我不想再创建另一个用于外观并再次遍历整个数组,因为我觉得这样效率很低。我想我很接近但不确定如何继续。感谢

2 个答案:

答案 0 :(得分:1)

创建初始数组的副本。

我最近做了类似的事情,这可能会有所帮助:

// Create copy to delete dups from
$copy = $sowArray; 
$sharedDescriptions = array();

for( $i=0; $i<count($sowArray); $i++ ) {
    if ( in_array( $sowArray[$i][$description], $sharedDescriptions ) ) {
        unset($copy[$i]);
    }
    else {
        $sharedDescriptions[] = $sowArray[$i][$description];
    }
}
$sharedDescriptions = array_values($sharedDescriptions);
$copy = array_values($copy);

// Update quantities of duplicate items
for( $i=0; $i<count($copy); $i++ ) {
    $product = $copy[$i][$description];
    $qty = 0;
    if (in_array($product, $sharedDescriptions)) {
        foreach ($sowArray as $sowRow) {
            if ($sowRow[$description] === $product){
                $qty += $sowRow[$quantity];
               }
            }
        $copy[$i][$quantity] = $qty;
        } 
    }

答案 1 :(得分:1)

这将有效:

var source = [['bourbon', 2], ['bourbon', 1],['scotch', 2]];
var hash = {};
var consolidated = [];

source.forEach(function(item) {
     hash[item[0]] = (hash[item[0]] || 0) + item[1];
});

Object.keys(hash).forEach(function(key) {
     consolidated.push([key, hash[key]]);
});

jsFiddle