How can I change elements position in a JS list?

118 Views Asked by At

I was trying to sort (based on dates) the elements in an array using the insertion sort algorithm, I think the problem is due to the nature of the element in the list, because when it comes to var x = A[i] or (outside the while) A[j + 1] = x the programme crashes and the Chrome console gives back

Uncaught TypeError: Failed to set an indexed property on HTMLCollection: Indexed property setter is not supported.

I'm new to JS so don't be ruthless to me Here's my code:

function insertion_sort(A) {
        var len = A.length;
        var i = 1;
        while (i < len) {
            var x = A[i];
            var j = i - 1;
            while (j >= 0 && dayjs(A[j].querySelector('span').innerText).format('YYYY-MM-DD') > dayjs(x.querySelector('span').innerText).format('YYYY-MM-DD')) {
                A[j + 1] = A[j];
                j = j - 1;
            }
            A[j + 1] = x;
            i = i + 1;
        }
        console.log(A);
    }
    
    let posts = [];
    
    posts = document.getElementsByTagName('article');
    
    insertion_sort(posts);
0

There are 0 best solutions below