John Char John Char - 27 days ago 6
Javascript Question

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:


  • I loop through each object and get "name" and push it in an array.

  • Then, I loop through the array and display each "name" to the place I
    want.



JSFIDDLE DEMO

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

Answer

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>