0

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
2
  • Which id should be kept? The first one found, or the last? Or do you not want to keep the id properties at all? Commented May 28, 2018 at 17:28
  • JQuery only slows down everything. For uniq results use Set Commented May 28, 2018 at 17:28

3 Answers 3

2

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 );

Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

0

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.