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

make sure values in array are unique when pushing

我使用 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);
});

有几种方法

1.Use _.uniq

_.uniq(productArray);

2.Use _.indexOfpushproductArray

之前

Example

为了数组的内容是唯一的,使用_.uniq怎么样?

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

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