DEV Community

Discussion on: 8 Best JavaScript One-Liners

Collapse
 
shivams1007 profile image
Shivam Singh

1. The sortBy Function with Repeated Identifiers

You're right that if two elements have the same identifier, the order doesn't matter for those particular elements. In many sorting algorithms, including JavaScript's native .sort(), elements that compare as equal remain in their original order (stable sort). So, your simplified version is equally effective:

const sortBy = (arr, key) => arr.sort((a, b) => a[key] > b[key] ? 1 : -1);
Enter fullscreen mode Exit fullscreen mode

This will work just fine even with repeated identifiers.

2. The splice Example and Array Mutation

I apologize for the misunderstanding. You're correct; your example using splice actually doesn't mutate the original array because you made a shallow copy (a=[...arr]) before applying the splice.

Here's the function for clarity:

const insert = (arr, index, newItem, a=[...arr]) => (a.splice(index, 0, newItem),a);
Enter fullscreen mode Exit fullscreen mode

In this function, a=[...arr] creates a new array that is a copy of the original arr. Then, splice is called on this new array (a), so the original arr remains unchanged. Therefore, it is a non-mutating operation on the original array.

Thank you for your keen observations; they serve to improve the quality and accuracy of the discussion.