Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to work with js arrays, finding and grouping items?

Googled around a fair bit but couldn't wrap my head around how to deal with this problem.

I have/plan a list of items.

var list1 = [
  [141,'AAA', 'A Group'],
  [262,'BBB', 'B Group'],
  [345,'CCC', 'B Group'],
  [136,'DDD'],
  [095,'EEE', 'A Group'],
  [175,'FFF'], and so on...
];

My goal is to print these items. Groups first, in alphabetical. Groupless after that.

All items in alphabetical.

Final result would be something like:

<div>

<h2>A Group</h2>
<ul class="group">
    <li>
        <img src="/141">
        <h3>AAA</h3>
    </li>
    <li>
        <img src="/095">
        <h3>EEE</h3>
    </li>
</ul>

<h2>B Group</h2>
<ul class="group">
    <li>
        <img src="/262">
        <h3>BBB</h3>
    </li>
    <li>
        <img src="/345">
        <h3>CCC</h3>
    </li>
</ul>

<h2>No group</h2>
<ul class="non-group">
    <li>
        <img src="/136">
        <h3>DDD</h3>
    </li>
    <li>
        <img src="/175">
        <h3>FFF</h3>
    </li>
</ul>

</div>

Any thoughts on how to tackle this?


Found this, https://stackoverflow.com/a/7596924/543365

Fairly close to what I could use. Couldn't manage to bend it to my use though.

like image 314
Xavio Avatar asked Dec 07 '25 03:12

Xavio


1 Answers

I would suggest looking into underscorejs, but, if you wish to use pure javascript:

1.) Sort the list so the items with a group come first.

var i = 0,
    group_arr = [];
for (i = 0; i < list1.length; i++) {
    if (list1[i][2] !== undefined) {
        group_arr.append(list1.splice(i, 1)[0]);
    }
}

2.) Now all the items with a group are in group_arr and the ones without are in list1. We need to now sort group_arr so it is in alphabetical order by group:

group_arr.sort(function (item1, item2) {
    return (item1[2] > item2[2]) ? 1 : -1;
});

Note that we can sort group_arr based on any arbitrary condition. If you would like to sort alphabetically by the second entry, just index that in the comparator function passed into Array.prototype.sort.

3.) Now the items in group_arr are in alphabetical order by group and contain items that have a group. Items in list 1 have no group and are not sorted. You can now iterate through each of these arrays, create your DOM elements and then insert them.

like image 117
Vinay Avatar answered Dec 08 '25 17:12

Vinay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!