Does Javascript filter preserve order?

Javascript

Javascript Problem Overview


I looked at the documentation and while looking at examples it looks like filter preserves order of the original list (though it returns a new one). Can I rely on that?

http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.20">Ecmascript spec

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter">MDN</a>

Neither of these reference preserving order. Should I just assume I can't rely on preserved order?

Javascript Solutions


Solution 1 - Javascript

Yes. From the spec,

> - Let selected be the result of calling the [[Call]] internal method of callbackfn with T as the this value and argument list containing kValue, k, and O. > - If ToBoolean(selected) is true, then > > - Call the [[DefineOwnProperty]] internal method of A with arguments ToString(to), Property Descriptor {[[Value]]: kValue, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true}, and false. > - Increase to by 1.

So the items in the returned array have the same order than in the original one.

Solution 2 - Javascript

Yes, the .filter() method returns a new array, without the filtered elements in the same order as initially.

The order of the elements is one of the main feature of a array.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionford prefectView Question on Stackoverflow
Solution 1 - JavascriptOriolView Answer on Stackoverflow
Solution 2 - JavascriptRikardView Answer on Stackoverflow