johnchar
johnchar

Reputation: 547

Extract data from Array of objects and Sort Alphabetically ( Simultaneously )

I have an array of objects:

var object = [
    {
        "id": 1,
        "name": "Vehicles"
    },
    ...

I want to extract the "name" from each object and sort it in an array of "names" and then display each "name".

This is how I do it:

JSFIDDLE DEMO

Is there a way to do both actions at the same time ?

Upvotes: 1

Views: 253

Answers (2)

adeneo
adeneo

Reputation: 318342

As you're already sorting and appending the values, the question is how to get rid of one of the loops, and not iterate twice.

You can map and sort, and just join the array to get rid of the last loop and append everything in one go

$(document).ready(function() {
    $('.lol').append(object.map(x => x.name).sort().join('<br />'));
});

var object = [{
    "id": 1,
    "name": "Vehicles"
}, {
    "id": 2,
    "name": "Mobiles & Tablets"
}, {
    "id": 3,
    "name": "Electronics & Appliances"
}, {
    "id": 4,
    "name": "Real Estate"
}, {
    "id": 5,
    "name": "Home & Lifestyle"
}, {
    "id": 6,
    "name": "Jobs"
}, {
    "id": 7,
    "name": "Services"
}, {
    "id": 8,
    "name": "Education & Training"
}, {
    "id": 9,
    "name": "Entertainment"
}, {
    "id": 10,
    "name": "Pet & Pet Care"
}, {
    "id": 11,
    "name": "Community"
}, {
    "id": 12,
    "name": "Events"
}, {
    "id": 13,
    "name": "Matrimonial"
}];
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="lol"></p>

Upvotes: 4

TimoStaudinger
TimoStaudinger

Reputation: 42520

A combination of map and sort will do the trick:

var items = [{
  "id": 1,
  "name": "Vehicles"
}, {
  "id": 2,
  "name": "Lizards"
}];

var names = items.map(function(item) {
  return item.name;
}).sort();

console.log(names); // ["Lizards", "Vehicles"]

Also note that the data you are using is not JSON, it is simply an array of JavaScript objects.

Upvotes: 4

Related Questions