user9294038
user9294038

Reputation: 141

Get unique data from array with jquery

I am fetching data from a big API with a lot of data. There is a lot of data with same building names that I need to output but I don't want all data to repeat itself I only want to display unique data.

How can I accomplish this?

var data = {
    "data": [{
        "id": 1,
        "building": "Big Building"
    }, {
        "id": 2,
        "building": "Big Building"
    }, {
        "id": 3,
        "building": "Small Building"
    }, {
        "id": 4,
        "building": "Small Building"
    }]
}

jQuery.each(data.data, function(index, item) {
    console.log(this['building']);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Result:

Big Building
Big Building
Small Building
Small Building

Wanted result:

Big Building
Small Building

Upvotes: 0

Views: 81

Answers (3)

Nishant Dixit
Nishant Dixit

Reputation: 5522

var response = {
"data": [
  {
     "id": 1,
     "building": "Big Building"
  },
  {
     "id": 2,
     "building": "Big Building"
  },
  {
     "id": 3,
     "building": "Small Building"
  },
  {
     "id": 4,
     "building": "Small Building"
  }
]};

var buildingArray = [];
var uniqueResponse = [];
for(i = 0; i< response.data.length; i++){    
    if(buildingArray.indexOf(response.data[i].building) === -1){
        uniqueResponse.push(response.data[i]);  
        buildingArray.push(response.data[i].building);
    }        
}
console.log(uniqueResponse);

Upvotes: 0

Eddie
Eddie

Reputation: 26844

You can use new Set to get the unique values. Use map to reiterate the array.

let data = {
  "data": [{"id": 1,"building": "Big Building"},
    {"id": 2,"building": "Big Building"},
    {"id": 3,"building": "Small Building"},
    {"id": 4,"building": "Small Building"}]
};

let result = [...new Set(data.data.map(o => o.building))];

console.log( result );

Upvotes: 2

brk
brk

Reputation: 50291

Using only javascript the same result can be acheived by using array reduce method & use indexOf.

var apiData = {
  "data": [{
      "id": 1,
      "building": "Big Building"
    },
    {
      "id": 2,
      "building": "Big Building"
    },
    {
      "id": 3,
      "building": "Small Building"
    },
    {
      "id": 4,
      "building": "Small Building"
    }
  ]
}

var unq = apiData.data.reduce(function(acc, curr) {
  // here acc is the empty array which is passed as thisArg
  // indexOf to check if the array contains the building name
  if (acc.indexOf(curr.building) === -1) {
    acc.push(curr.building)
  }
  return acc;

}, [])

console.log(unq)

Upvotes: 0

Related Questions