1

I push in values from JSON into a several arrays using Underscore, but I want to eliminate any repeated values if there are any, either during push or after. How could I do this?

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 (Underscore)

var productArrays = [];
_.each(looks, function(look) {
  var productArray = [];
  _.each(look.products, function(product) {
    productArray.push(product.replace(/_.*/, ''))
  })
  productArrays.push(productArray);
});
user1937021
  • 10,151
  • 22
  • 81
  • 143

2 Answers2

3

There are couple ways

1.Use _.uniq

_.uniq(productArray);

2.Use _.indexOf before push to productArray

Example

Oleksandr T.
  • 76,493
  • 17
  • 173
  • 144
1

For array's content be unique, how about using _.uniq?

Or just check existence of value before really push it.

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