A
A
avtor_house2019-03-04 07:08:27
JavaScript
avtor_house, 2019-03-04 07:08:27

How to sort div blocks by text inside?

Hello everyone, there is such a data output structure from php

<?php foreach ($accounts as $account): ?>
                <div id="<?= $account['activation'];  ?>" class="item">
                    <a href="<?= $account['idn'] . $account['href'] ?>">
                        <img src="<?= $account['img'] ?>" alt="Купить <?= $account['name'] ?>" title="Купить <?= $account['name'] ?>">
                        <div class="item_overlay">
                            <div class="item_title">
                                <span class="<?= mb_strtolower($account['activation']);  ?>"></span>
                                <span class="searchable"><?= $account['name'] ?></span>
                            </div>
                        </div>
                        <div class="item_price">от <span><?= $account['min_price'] ?></span> ₽</div>
                    </a>
                </div>
            <?php endforeach ?>

How to make it so that when you click on a button or link (it doesn't matter), sorting by name or price occurs. And the button worked both ascending and descending. By the way, the site is written in Angular, and if you can sort using Angular, please write how, otherwise I don’t understand it. Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Moses Fender, 2019-03-04
@avtor_house

JavaScript has the traditional sort() function in the array prototype.
For example, let's make a table like this:

<a href="javascript:" data-sort="alphabet">sort by alpabet</a>
<a href="javascript:" data-sort="amount">sort by amount</a>

<div id="lst">
    <div><span>jsghgori</span><span>345</span></div>
    <div><span>ouerok</span><span>98</span></div>
    <div><span>qiewhfh</span><span>548</span></div>
    <div><span>nvxcmk</span><span>234</span></div>
    <div><span>kefoo</span><span>38</span></div>
</div>

Now we will stuff it with functionality for sorting and drawing:
<script>
    var lst = document.getElementById('lst');
    Object.defineProperties(lst, {
        _direct: {
            /**
             *  Направление сортировки
             *  0 - a->z
             *  1 - z->a
             */
            value: 0,
            writable: true
        },

        direct: {
            get: function () {
                return this._direct;
            },
            set: function (val) {
                this._direct = Math.abs(this._direct - 1);
            },
            enumerable: true,
            configurable: true
        },
        _dataArr: {
            /* Массив с данными */
            value: [],
            writable: true,
        },
        data: {
            /* Получить массив с данными */
            get: function () {
                let _that = this;
                if (!this._dataArr.length) {
                    /* Если массив пуст, получим данные */
                    [].map.call(this.children, function (_row) {
                        let _dataRow = {
                            title: _row.children[0].innerHTML,
                            amount: parseInt(_row.children[1].innerHTML),
                            element: _row
                        }
                        _that._dataArr.push(_dataRow);
                    });
                }
                /* В любом случае возвертаем массив */
                return this._dataArr;
            }
        },
        sortByAlphabet: {
            value: function () {
                let _that = this;
                this.data.sort(function (a, b) {
                    if (_that.direct) {
                        return a.title > b.title ? 1 : -1;
                    } else {
                        return a.title > b.title ? -1 : 1;
                    }
                });

                this.direct = true;
                this.drawRows();
            },
            writable: false
        },
        sortByAmount: {
            value: function () {
                let _that = this;
                this.data.sort(function (a, b) {
                    if (_that.direct) {
                        return a.amount > b.amount ? 1 : -1;
                    } else {
                        return a.amount > b.amount ? -1 : 1;
                    }
                });
                this.direct = true;
                this.drawRows();
            },
            writable: false
        },
        drawRows: {
            value: function () {
                for (let i = 0; i < this.data.length; i++) {
                    this.appendChild(this.removeChild(this.data[i].element));
                }
            },
            writable: false
        }
    });
    document.addEventListener('click', function (ev) {
        if (ev.target.hasAttribute('data-sort')) {
            switch (ev.target.getAttribute('data-sort')) {
                case 'alphabet':
                    lst.sortByAlphabet();
                    break;
                case 'amount':
                    lst.sortByAmount();
                    break;
            }
        }
    });
</script>

It's all in lst.sortByAlphabet() and lst.sortByAmount(). That is, sort() internally iterates over all the elements of the array with its neighbor, passing them in arguments, which is what we use to compare them. What to compare, we decide for ourselves.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question