确保数组中的值在推送时是唯一的

时间:2015-03-05 08:26:25

标签: javascript jquery underscore.js

我使用Underscore将JSON中的值推入到几个数组中,但是如果有任何重复值,我想在推送期间或之后消除任何重复值。我怎么能这样做?

JSON

looks = [{
        "id": "look1",
        "products": ["hbeu50271385", "hbeu50274296", "hbeu50272359", "hbeu50272802"]
    }, {
        "id": "look2",
        "products": [
            "hbeu50274106", "hbeu50273647", "hbeu50274754", "hbeu50274063", "hbeu50274911", "hbeu50274106", "hbeu50240022", "hbeu50271944"
        ]
    }, {
        "id": "look3",
        "products": [
            "hbeu50272935", "hbeu50274426", "hbeu50271624", "hbeu50274762", "hbeu50275366", "hbeu50274433", "hbeu50262002", "hbeu50272364", "hbeu50272359"
        ]
    }
    .......
]

JS(下划线)

var productArrays = [];
_.each(looks, function(look) {
  var productArray = [];
  _.each(look.products, function(product) {
    productArray.push(product.replace(/_.*/, ''))
  })
  productArrays.push(productArray);
});

2 个答案:

答案 0 :(得分:3)

有几种方式

1.使用_.uniq

_.uniq(productArray);

2.在pushproductArray

之前使用_.indexOf

Example

答案 1 :(得分:1)

对于数组的内容是唯一的,如何使用_.uniq?

或者在真正推动之前检查是否存在价值。

function uniquePush(arr, valueToPush) {
    if(arr.indexOf(valueToPush) == -1) {
        arr.push(valueToPush)
    }
}