JavaScript Mapping Library
Manipulating data is core to any programming language. JavaScript is no exception, especially as JSON has token over as a prime data delivery format. One such data manipulation is reversing arrays. You may want to reverse an array to show most recent transactions, or simple alphabetic sorting.
Reversing arrays with JavaScript originally was done via reverse but that would mutate the original array:
reverse
// First value: const arr = ['hi', 'low', 'ahhh']; // Reverse it without reassigning: arr.reverse(); // Value: arr (3) ['ahhh', 'low', 'hi']
Modifying the original array is a legacy methodology. To avoid this mutation, we’d copy the array and then reverse it:
const reversed = [...arr].reverse();
These days we can use toReversed to avoid mutating the original array:
toReversed
const arr = ['hi', 'low', 'ahhh']; const reversed = arr.toReversed(); // (3) ['ahhh', 'low', 'hi']; arr; // ['hi', 'low', 'ahhh']
Avoiding mutation of data objects is incredibly important in a programming language like JavaScript where object references are meaningful.
The post JavaScript: Reverse Arrays appeared first on David Walsh Blog.
David Walsh Blog
You must be logged in to post a comment.
This site uses Akismet to reduce spam. Learn how your comment data is processed.