Nikhil Menghrajani Nikhil Menghrajani - 6 months ago 15
AngularJS Question

How to save distinct values in an object in javascript?

I have a bunch of log data which is stored in a variable. Each log value contains a camera name and system ip. I want to create an object which has names as all the distinct system ip's and corresponding value as an array which contains all the camera names corresponding to that system ip. Below is my code ---

$scope.logs = data;
var v =$scope.logs[0].systemIp;
var flag=0;
for(j in $scope.cameras){
else if(flag==1)

And this is what my data looks like --

"_id": "57683fd82c77bb5a1a49a2aa",
"cameraIp": "",
"cameraName": "garage2",
"systemIp": ""
"_id": "57683f8e2c77bb5a1a49a2a9",
"cameraIp": "",
"cameraName": "garage1",
"systemIp": ""
"_id": "57683f5e2c77bb5a1a49a2a8",
"cameraIp": "",
"cameraName": "Back Door",
"systemIp": ""

When I print $scope.cameras on my console it gives this as the output -

Object { v: Array[3] }

I want by cameras object to look like this --

{ "" : [ "garage1" , "garage2"] ,
"" : [ "Back Door"] }

I am new to javascript, any help is appreciated.


If you are using the Lodash or Underscore library (which I highly recommend), you can just use the _.groupBy() function to do what you are after (along with some other functions to ensure all values are unique).

However, you can also easily implement it yourself:

function groupByDistinct(arr, prop, mapFn) {
    mapFn = mapFn || function (x) { return x; };
    var output = {};
    arr.forEach(function (item) {
        var key = item[prop],
            val = mapFn(item);
        if (!output[key]) {
            output[key] = [val];
        if (output[key].indexOf(val) < 0) {
    return output;

Use it for your code like so:

$scope.cameras = groupByDistinct(data, 'cameraIp', function (logEntry) { 
    return logEntry.cameraName;