0

I have a Json array.

 "user": {
            "value": [
                {

                    "customerNo": "1234"

                },
                {
                    "customerNo": "abcd"

                },
                {

                    "customerNo": "1234"

                }

            ]
        }

Here I want to get the count of total number of customer. I am getting it like this:

json.user.value.length;

And the output is 3. But the thing is I have to avoid duplicate customer number.

As here "1234" is there 2 times. So my output should be 2 How to do this using Typescript.

halfer
  • 19,824
  • 17
  • 99
  • 186
ananya
  • 1,001
  • 6
  • 33
  • 50
  • 1
    @Moriarty: I am not sure the `angular` tag was irrelevant - there was a comment above which used a `forEach` device in Angular (now deleted, for reasons I don't know). – halfer Aug 23 '17 at 10:00
  • @halfer Haven't seen it, but no problem if it has to be re-added again when the question changes. – Juliën Aug 23 '17 at 10:02

2 Answers2

2

Use lodash:

var uniqueCustomer = _.uniqBy(json.user.value, 'customerNo');
var length = uniqueCustomer.length

Here is link which shows How to use lodash in your app.

FAISAL
  • 33,618
  • 10
  • 97
  • 105
Gaurav Sharma
  • 411
  • 7
  • 22
0

You can use Array.reduce to count the unique customers.

const data = { 
  "user": {
      "value": [
          {

              "customerNo": "1234"

          },
          {
              "customerNo": "abcd"

          },
          {

              "customerNo": "1234"

          }

      ]
  }
};

function getCustomerCount(arr) {
  let tmp = [];
  return arr.reduce((acc, curr) => {
    if(!tmp.includes(curr.customerNo)) {
      return tmp.push(curr.customerNo);
    }
    return acc;
  }, 0);
}

let customers = data.user.value;
let customerCount = getCustomerCount(customers);

console.log(customerCount);
cyr_x
  • 13,987
  • 2
  • 32
  • 46