foreach in reverse order

2,764 views
Skip to first unread message

Dražen Perić

unread,
Sep 3, 2012, 12:05:33 PM9/3/12
to knock...@googlegroups.com
Is it possible to print array values (with foreach) in reverse order?

Let's say I have this example:
someArray = [0, 1, 2, 3];
self.someArray = ko.observableArray(someArray );

If I print that with foreach, it'll look like:
0
1
2

But, is it possible to print in reverse order, so it can look like:
2
1
0

I know how to do that with for statement, but inside html is possible to use only knockout js foreach statement.

rpn

unread,
Sep 3, 2012, 2:09:54 PM9/3/12
to knock...@googlegroups.com
You can do something like this to create a copy of the array and reverse it in the binding:

<ul data-bind="foreach: items.slice(0).reverse()">
    <li data-bind="text: id"></li>
</ul>
Message has been deleted

Drazen

unread,
Sep 3, 2012, 2:15:55 PM9/3/12
to knock...@googlegroups.com
Thanks, it works if I put just .reverse().

But on the other side, I'm wondering, how complexed is that, if I reverse my array every time I "print" it? Because this is actually sorting, and sorting is pretty "expensive", in time complexity, right?

Thanks

Michael Best

unread,
Sep 3, 2012, 2:47:44 PM9/3/12
to knock...@googlegroups.com
I recently added a "reverse" option to my repeat binding. So then you could do this:

<ul>
    <li data-bind="repeat: { foreach: items, reverse: true }" data-repeat-bind="text: $item().id"></li>
</ul> 

-- Michael

maxf...@gmail.com

unread,
Mar 20, 2013, 12:44:58 PM3/20/13
to knock...@googlegroups.com
I think what you may want is myarray.unshift(newelement) that way you put in front.


On Monday, September 3, 2012 11:05:33 AM UTC-5, Drazen wrote:
Reply all
Reply to author
Forward
0 new messages