diff --git a/docs/ja/reference/array/orderBy.md b/docs/ja/reference/array/orderBy.md index c4119102d..1ccab0cf1 100644 --- a/docs/ja/reference/array/orderBy.md +++ b/docs/ja/reference/array/orderBy.md @@ -1,6 +1,6 @@ # orderBy -複数の基準と並び順に従って、オブジェクト配列をソートした新しい配列を返します。 +複数の基準と並び順に従って、配列をソートした新しい配列を返します。 ```typescript const sorted = orderBy(arr, criteria, orders); @@ -10,11 +10,31 @@ const sorted = orderBy(arr, criteria, orders); ### `orderBy(arr, criteria, orders)` -オブジェクト配列を複数の条件で複合ソートしたい場合は `orderBy` を使用してください。各条件ごとに昇順または降順を指定でき、前の条件で同じ値の場合は次の条件でソートします。 +配列を複数の条件で複合ソートしたい場合は `orderBy` を使用してください。各条件ごとに昇順または降順を指定でき、前の条件で同じ値の場合は次の条件でソートします。 ```typescript import { orderBy } from 'es-toolkit/array'; +// 文字列配列をソート +const strings = ['banana', 'apple', 'cherry']; +orderBy(strings, [], ['desc']); +// Returns: ['cherry', 'banana', 'apple'] + +// 文字列を長さでソート +const strings = ['banana', 'a', 'cherry']; +orderBy(strings, [x => x.length], ['asc']); +// Returns: ['a', 'cherry', 'banana'] + +// 大文字小文字を区別せずにソート +const strings = ['Banana', 'apple', 'Cherry']; +orderBy(strings, [x => x.toLowerCase()], ['asc']); +// Returns: ['apple', 'Banana', 'Cherry'] + +// 数値配列をソート +const numbers = [3, 1, 4, 1, 5, 9]; +orderBy(numbers, [], ['desc']); +// Returns: [9, 5, 4, 3, 1, 1] + // 複数の基準でユーザー配列をソートします。 const users = [ { user: 'fred', age: 48 }, @@ -60,9 +80,9 @@ orderBy(data, ['a', 'b', 'c'], ['asc', 'desc']); #### パラメータ -- `arr` (`T[]`): ソートするオブジェクト配列です。 -- `criteria` (`Array<((item: T) => unknown) | keyof T>`): ソートする基準です。オブジェクトのプロパティ名または値を返す関数を使用できます。 -- `orders` (`Array<'asc' | 'desc'>`): 各基準に対する並び順の配列です。`'asc'`は昇順、`'desc'`は降順を意味します。 +- `arr` (`readonly T[]`): ソートする配列です。 +- `criteria` (`Array<((item: T) => unknown) | keyof T>`, オプション): ソートする基準です。オブジェクトのプロパティ名または値を返す関数を使用できます。指定しないか空配列の場合、プリミティブ型の値そのものでソートします。 +- `orders` (`Array<'asc' | 'desc'>`, オプション): 各基準に対する並び順の配列です。`'asc'`は昇順、`'desc'`は降順を意味します。デフォルトは `['asc']` です。 #### 戻り値 diff --git a/docs/ja/reference/array/sortBy.md b/docs/ja/reference/array/sortBy.md index 4022935cd..84bc0f342 100644 --- a/docs/ja/reference/array/sortBy.md +++ b/docs/ja/reference/array/sortBy.md @@ -1,6 +1,6 @@ # sortBy -与えられた基準に従ってオブジェクト配列を昇順にソートした新しい配列を返します。 +与えられた基準に従って配列を昇順にソートした新しい配列を返します。 ```typescript const sorted = sortBy(arr, criteria); @@ -10,11 +10,31 @@ const sorted = sortBy(arr, criteria); ### `sortBy(arr, criteria)` -オブジェクト配列を複数のプロパティまたは計算された値を基準にソートしたい場合は `sortBy` を使用してください。プロパティ名または変換関数を配列で提供すると、その順序で優先順位を付けて昇順にソートします。テーブルデータをソートしたり、複雑なソートロジックが必要なときに便利です。 +配列を複数のプロパティまたは計算された値を基準にソートしたい場合は `sortBy` を使用してください。プロパティ名または変換関数を配列で提供すると、その順序で優先順位を付けて昇順にソートします。テーブルデータをソートしたり、複雑なソートロジックが必要なときに便利です。 ```typescript import { sortBy } from 'es-toolkit/array'; +// 文字列配列をソート +const strings = ['banana', 'apple', 'cherry']; +sortBy(strings); +// Returns: ['apple', 'banana', 'cherry'] + +// 文字列を長さでソート +const strings = ['banana', 'a', 'cherry']; +sortBy(strings, [x => x.length]); +// Returns: ['a', 'cherry', 'banana'] + +// 大文字小文字を区別せずにソート +const strings = ['Banana', 'apple', 'Cherry']; +sortBy(strings, [x => x.toLowerCase()]); +// Returns: ['apple', 'Banana', 'Cherry'] + +// 数値配列をソート +const numbers = [3, 1, 4, 1, 5, 9]; +sortBy(numbers); +// Returns: [1, 1, 3, 4, 5, 9] + // 単一のプロパティでソートします。 const users = [ { name: 'john', age: 30 }, @@ -55,23 +75,20 @@ const products = [ const sorted = sortBy(products, [ 'category', - item => -item.price, // 価格は降順で + item => -item.price, // 価格は降順で(負数変換) ]); // Returns: カテゴリが最初、次に価格の高い順でソート // 計算された値でソートします。 const words = ['hello', 'a', 'wonderful', 'world']; -const byLength = sortBy( - words.map(word => ({ word, length: word.length })), - ['length'] -); -// Returns: 文字列の長さ順でソートされたオブジェクト配列 +const byLength = sortBy(words, [word => word.length]); +// Returns: ['a', 'hello', 'world', 'wonderful'] ``` #### パラメータ -- `arr` (`readonly T[]`): ソートするオブジェクト配列です。 -- `criteria` (`Array<((item: T) => unknown) | keyof T>`): ソート基準です。オブジェクトのプロパティ名または変換関数の配列で、前にある基準が優先順位が高くなります。 +- `arr` (`readonly T[]`): ソートする配列です。 +- `criteria` (`Array<((item: T) => unknown) | keyof T>`, オプション): ソート基準です。オブジェクトのプロパティ名または変換関数の配列で、前にある基準が優先順位が高くなります。指定しないか空配列の場合、プリミティブ型の値そのものでソートします。 #### 戻り値 diff --git a/docs/ko/reference/array/orderBy.md b/docs/ko/reference/array/orderBy.md index 6d2bc856c..c2f7a2310 100644 --- a/docs/ko/reference/array/orderBy.md +++ b/docs/ko/reference/array/orderBy.md @@ -1,6 +1,6 @@ # orderBy -여러 기준과 정렬 방향에 따라 객체 배열을 정렬한 새 배열을 반환해요. +여러 기준과 정렬 방향에 따라 배열을 정렬한 새 배열을 반환해요. ```typescript const sorted = orderBy(arr, criteria, orders); @@ -10,11 +10,31 @@ const sorted = orderBy(arr, criteria, orders); ### `orderBy(arr, criteria, orders)` -객체 배열을 여러 조건으로 복합 정렬하고 싶을 때 `orderBy`를 사용하세요. 각 조건마다 오름차순이나 내림차순을 지정할 수 있고, 앞의 조건에서 같은 값이면 다음 조건으로 정렬해요. +배열을 여러 조건으로 복합 정렬하고 싶을 때 `orderBy`를 사용하세요. 각 조건마다 오름차순이나 내림차순을 지정할 수 있고, 앞의 조건에서 같은 값이면 다음 조건으로 정렬해요. ```typescript import { orderBy } from 'es-toolkit/array'; +// 문자열 배열 정렬하기 +const strings = ['banana', 'apple', 'cherry']; +orderBy(strings, [], ['desc']); +// Returns: ['cherry', 'banana', 'apple'] + +// 문자열을 길이로 정렬하기 +const strings = ['banana', 'a', 'cherry']; +orderBy(strings, [x => x.length], ['asc']); +// Returns: ['a', 'cherry', 'banana'] + +// 대소문자 구분 없이 정렬하기 +const strings = ['Banana', 'apple', 'Cherry']; +orderBy(strings, [x => x.toLowerCase()], ['asc']); +// Returns: ['apple', 'Banana', 'Cherry'] + +// 숫자 배열 정렬하기 +const numbers = [3, 1, 4, 1, 5, 9]; +orderBy(numbers, [], ['desc']); +// Returns: [9, 5, 4, 3, 1, 1] + // 여러 기준으로 사용자 배열을 정렬해요. const users = [ { user: 'fred', age: 48 }, @@ -60,9 +80,9 @@ orderBy(data, ['a', 'b', 'c'], ['asc', 'desc']); #### 파라미터 -- `arr` (`T[]`): 정렬할 객체 배열이에요. -- `criteria` (`Array<((item: T) => unknown) | keyof T>`): 정렬할 기준들이에요. 객체의 속성 이름이나 값을 반환하는 함수를 사용할 수 있어요. -- `orders` (`Array<'asc' | 'desc'>`): 각 기준에 대한 정렬 방향 배열이에요. `'asc'`는 오름차순, `'desc'`는 내림차순을 의미해요. +- `arr` (`readonly T[]`): 정렬할 배열이에요. +- `criteria` (`Array<((item: T) => unknown) | keyof T>`, optional): 정렬할 기준들이에요. 객체의 속성 이름이나 값을 반환하는 함수를 사용할 수 있어요. 제공하지 않거나 빈 배열이면 원시 타입을 그 자체로 정렬해요. +- `orders` (`Array<'asc' | 'desc'>`, optional): 각 기준에 대한 정렬 방향 배열이에요. `'asc'`는 오름차순, `'desc'`는 내림차순을 의미해요. 기본값은 `['asc']`예요. #### 반환 값 diff --git a/docs/ko/reference/array/sortBy.md b/docs/ko/reference/array/sortBy.md index 4e1cad0b4..b851620a6 100644 --- a/docs/ko/reference/array/sortBy.md +++ b/docs/ko/reference/array/sortBy.md @@ -1,6 +1,6 @@ # sortBy -주어진 기준에 따라 객체 배열을 오름차순으로 정렬한 새 배열을 반환해요. +주어진 기준에 따라 배열을 오름차순으로 정렬한 새 배열을 반환해요. ```typescript const sorted = sortBy(arr, criteria); @@ -10,11 +10,31 @@ const sorted = sortBy(arr, criteria); ### `sortBy(arr, criteria)` -객체 배열을 여러 속성이나 계산된 값을 기준으로 정렬하고 싶을 때 `sortBy`를 사용하세요. 속성 이름이나 변환 함수를 배열로 제공하면, 해당 순서대로 우선순위를 두고 오름차순으로 정렬해요. 테이블 데이터를 정렬하거나 복잡한 정렬 로직이 필요할 때 유용해요. +배열을 여러 속성이나 계산된 값을 기준으로 정렬하고 싶을 때 `sortBy`를 사용하세요. 속성 이름이나 변환 함수를 배열로 제공하면, 해당 순서대로 우선순위를 두고 오름차순으로 정렬해요. 테이블 데이터를 정렬하거나 복잡한 정렬 로직이 필요할 때 유용해요. ```typescript import { sortBy } from 'es-toolkit/array'; +// 문자열 배열 정렬하기 +const strings = ['banana', 'apple', 'cherry']; +sortBy(strings); +// Returns: ['apple', 'banana', 'cherry'] + +// 문자열을 길이로 정렬하기 +const strings = ['banana', 'a', 'cherry']; +sortBy(strings, [x => x.length]); +// Returns: ['a', 'cherry', 'banana'] + +// 대소문자 구분 없이 정렬하기 +const strings = ['Banana', 'apple', 'Cherry']; +sortBy(strings, [x => x.toLowerCase()]); +// Returns: ['apple', 'Banana', 'Cherry'] + +// 숫자 배열 정렬하기 +const numbers = [3, 1, 4, 1, 5, 9]; +sortBy(numbers); +// Returns: [1, 1, 3, 4, 5, 9] + // 단일 속성으로 정렬해요. const users = [ { name: 'john', age: 30 }, @@ -55,23 +75,20 @@ const products = [ const sorted = sortBy(products, [ 'category', - item => -item.price, // 가격은 내림차순으로 + item => -item.price, // 가격은 내림차순으로 (음수 변환) ]); // Returns: 카테고리 먼저, 그 다음 가격 높은 순으로 정렬 // 계산된 값으로 정렬해요. const words = ['hello', 'a', 'wonderful', 'world']; -const byLength = sortBy( - words.map(word => ({ word, length: word.length })), - ['length'] -); -// Returns: 문자열 길이 순으로 정렬된 객체 배열 +const byLength = sortBy(words, [word => word.length]); +// Returns: ['a', 'hello', 'world', 'wonderful'] ``` #### 파라미터 -- `arr` (`readonly T[]`): 정렬할 객체 배열이에요. -- `criteria` (`Array<((item: T) => unknown) | keyof T>`): 정렬 기준이에요. 객체 속성 이름이나 변환 함수의 배열로, 앞에 있는 기준이 우선순위가 높아요. +- `arr` (`readonly T[]`): 정렬할 배열이에요. +- `criteria` (`Array<((item: T) => unknown) | keyof T>`, optional): 정렬 기준이에요. 객체 속성 이름이나 변환 함수의 배열로, 앞에 있는 기준이 우선순위가 높아요. 제공하지 않거나 빈 배열이면 원시 타입을 그 자체로 정렬해요. #### 반환 값 diff --git a/docs/reference/array/orderBy.md b/docs/reference/array/orderBy.md index 729c8342b..7b1fb3cd0 100644 --- a/docs/reference/array/orderBy.md +++ b/docs/reference/array/orderBy.md @@ -10,11 +10,31 @@ const sorted = orderBy(arr, criteria, orders); ### `orderBy(arr, criteria, orders)` -Use `orderBy` when you want to perform compound sorting on an array of objects with multiple conditions. You can specify ascending or descending order for each criterion, and if values are the same for the first criterion, it sorts by the next criterion. +Use `orderBy` when you want to perform compound sorting on an array with multiple conditions. You can specify ascending or descending order for each criterion, and if values are the same for the first criterion, it sorts by the next criterion. ```typescript import { orderBy } from 'es-toolkit/array'; +// Sort an array of strings +const strings = ['banana', 'apple', 'cherry']; +orderBy(strings, [], ['desc']); +// Returns: ['cherry', 'banana', 'apple'] + +// Sort strings by length +const strings = ['banana', 'a', 'cherry']; +orderBy(strings, [x => x.length], ['asc']); +// Returns: ['a', 'cherry', 'banana'] + +// Sort strings case-insensitively +const strings = ['Banana', 'apple', 'Cherry']; +orderBy(strings, [x => x.toLowerCase()], ['asc']); +// Returns: ['apple', 'Banana', 'Cherry'] + +// Sort an array of numbers +const numbers = [3, 1, 4, 1, 5, 9]; +orderBy(numbers, [], ['desc']); +// Returns: [9, 5, 4, 3, 1, 1] + // Sort a user array by multiple criteria. const users = [ { user: 'fred', age: 48 }, @@ -60,9 +80,9 @@ orderBy(data, ['a', 'b', 'c'], ['asc', 'desc']); #### Parameters -- `arr` (`T[]`): The array of objects to sort. -- `criteria` (`Array<((item: T) => unknown) | keyof T>`): The criteria to sort by. You can use property names of objects or functions that return values. -- `orders` (`Array<'asc' | 'desc'>`): An array of sort directions for each criterion. `'asc'` means ascending order, `'desc'` means descending order. +- `arr` (`readonly T[]`): The array to sort. +- `criteria` (`Array<((item: T) => unknown) | keyof T>`, optional): The criteria to sort by. You can use property names of objects or functions that return values. If not provided or empty, sorts primitives by their own values. +- `orders` (`Array<'asc' | 'desc'>`, optional): An array of sort directions for each criterion. `'asc'` means ascending order, `'desc'` means descending order. Defaults to `['asc']`. #### Returns diff --git a/docs/reference/array/sortBy.md b/docs/reference/array/sortBy.md index e5f1b645e..62a01e543 100644 --- a/docs/reference/array/sortBy.md +++ b/docs/reference/array/sortBy.md @@ -10,11 +10,31 @@ const sorted = sortBy(arr, criteria); ### `sortBy(arr, criteria)` -Use `sortBy` when you want to sort an array of objects by multiple properties or computed values. Provide property names or transformation functions as an array, and it sorts in ascending order with priority in that order. It's useful for sorting table data or when complex sorting logic is needed. +Use `sortBy` when you want to sort an array by multiple properties or computed values. Provide property names or transformation functions as an array, and it sorts in ascending order with priority in that order. It's useful for sorting table data or when complex sorting logic is needed. ```typescript import { sortBy } from 'es-toolkit/array'; +// Sort an array of strings +const strings = ['banana', 'apple', 'cherry']; +sortBy(strings); +// Returns: ['apple', 'banana', 'cherry'] + +// Sort strings by length +const strings = ['banana', 'a', 'cherry']; +sortBy(strings, [x => x.length]); +// Returns: ['a', 'cherry', 'banana'] + +// Sort strings case-insensitively +const strings = ['Banana', 'apple', 'Cherry']; +sortBy(strings, [x => x.toLowerCase()]); +// Returns: ['apple', 'Banana', 'Cherry'] + +// Sort an array of numbers +const numbers = [3, 1, 4, 1, 5, 9]; +sortBy(numbers); +// Returns: [1, 1, 3, 4, 5, 9] + // Sort by a single property. const users = [ { name: 'john', age: 30 }, @@ -55,23 +75,20 @@ const products = [ const sorted = sortBy(products, [ 'category', - item => -item.price, // Sort price in descending order + item => -item.price, // Sort price in descending order (negative conversion) ]); // Returns: Sort by category first, then by highest price // Sort by computed values. const words = ['hello', 'a', 'wonderful', 'world']; -const byLength = sortBy( - words.map(word => ({ word, length: word.length })), - ['length'] -); -// Returns: Array of objects sorted by string length +const byLength = sortBy(words, [word => word.length]); +// Returns: ['a', 'hello', 'world', 'wonderful'] ``` #### Parameters -- `arr` (`readonly T[]`): The array of objects to sort. -- `criteria` (`Array<((item: T) => unknown) | keyof T>`): Sorting criteria. An array of object property names or transformation functions, with earlier criteria having higher priority. +- `arr` (`readonly T[]`): The array to sort. +- `criteria` (`Array<((item: T) => unknown) | keyof T>`, optional): Sorting criteria. An array of object property names or transformation functions, with earlier criteria having higher priority. If not provided or empty, sorts primitives by their own values. #### Returns diff --git a/docs/zh_hans/reference/array/orderBy.md b/docs/zh_hans/reference/array/orderBy.md index 0b4b2338f..c6165cd29 100644 --- a/docs/zh_hans/reference/array/orderBy.md +++ b/docs/zh_hans/reference/array/orderBy.md @@ -1,6 +1,6 @@ # orderBy -根据多个标准和排序方向对对象数组进行排序,返回一个新数组。 +根据多个标准和排序方向对数组进行排序,返回一个新数组。 ```typescript const sorted = orderBy(arr, criteria, orders); @@ -10,11 +10,31 @@ const sorted = orderBy(arr, criteria, orders); ### `orderBy(arr, criteria, orders)` -当您想对对象数组进行多条件复合排序时,请使用 `orderBy`。可以为每个条件指定升序或降序,如果前面的条件值相同,则按下一个条件排序。 +当您想对数组进行多条件复合排序时,请使用 `orderBy`。可以为每个条件指定升序或降序,如果前面的条件值相同,则按下一个条件排序。 ```typescript import { orderBy } from 'es-toolkit/array'; +// 对字符串数组排序 +const strings = ['banana', 'apple', 'cherry']; +orderBy(strings, [], ['desc']); +// Returns: ['cherry', 'banana', 'apple'] + +// 按字符串长度排序 +const strings = ['banana', 'a', 'cherry']; +orderBy(strings, [x => x.length], ['asc']); +// Returns: ['a', 'cherry', 'banana'] + +// 不区分大小写排序 +const strings = ['Banana', 'apple', 'Cherry']; +orderBy(strings, [x => x.toLowerCase()], ['asc']); +// Returns: ['apple', 'Banana', 'Cherry'] + +// 对数字数组排序 +const numbers = [3, 1, 4, 1, 5, 9]; +orderBy(numbers, [], ['desc']); +// Returns: [9, 5, 4, 3, 1, 1] + // 根据多个标准对用户数组进行排序 const users = [ { user: 'fred', age: 48 }, @@ -60,9 +80,9 @@ orderBy(data, ['a', 'b', 'c'], ['asc', 'desc']); #### 参数 -- `arr` (`T[]`): 要排序的对象数组。 -- `criteria` (`Array<((item: T) => unknown) | keyof T>`): 排序标准。可以使用对象的属性名或返回值的函数。 -- `orders` (`Array<'asc' | 'desc'>`): 每个标准的排序方向数组。`'asc'` 表示升序,`'desc'` 表示降序。 +- `arr` (`readonly T[]`): 要排序的数组。 +- `criteria` (`Array<((item: T) => unknown) | keyof T>`, 可选): 排序标准。可以使用对象的属性名或返回值的函数。如果未提供或为空数组,则按原始类型的值本身排序。 +- `orders` (`Array<'asc' | 'desc'>`, 可选): 每个标准的排序方向数组。`'asc'` 表示升序,`'desc'` 表示降序。默认为 `['asc']`。 #### 返回值 diff --git a/docs/zh_hans/reference/array/sortBy.md b/docs/zh_hans/reference/array/sortBy.md index 27a7d6e35..1ff973e45 100644 --- a/docs/zh_hans/reference/array/sortBy.md +++ b/docs/zh_hans/reference/array/sortBy.md @@ -1,6 +1,6 @@ # sortBy -根据给定的标准对对象数组进行升序排序,返回一个新数组。 +根据给定的标准对数组进行升序排序,返回一个新数组。 ```typescript const sorted = sortBy(arr, criteria); @@ -10,11 +10,31 @@ const sorted = sortBy(arr, criteria); ### `sortBy(arr, criteria)` -当您想根据多个属性或计算值对对象数组进行排序时,请使用 `sortBy`。提供属性名或转换函数的数组,会按照该顺序设置优先级并进行升序排序。在对表格数据排序或需要复杂排序逻辑时非常有用。 +当您想根据多个属性或计算值对数组进行排序时,请使用 `sortBy`。提供属性名或转换函数的数组,会按照该顺序设置优先级并进行升序排序。在对表格数据排序或需要复杂排序逻辑时非常有用。 ```typescript import { sortBy } from 'es-toolkit/array'; +// 对字符串数组排序 +const strings = ['banana', 'apple', 'cherry']; +sortBy(strings); +// Returns: ['apple', 'banana', 'cherry'] + +// 按字符串长度排序 +const strings = ['banana', 'a', 'cherry']; +sortBy(strings, [x => x.length]); +// Returns: ['a', 'cherry', 'banana'] + +// 不区分大小写排序 +const strings = ['Banana', 'apple', 'Cherry']; +sortBy(strings, [x => x.toLowerCase()]); +// Returns: ['apple', 'Banana', 'Cherry'] + +// 对数字数组排序 +const numbers = [3, 1, 4, 1, 5, 9]; +sortBy(numbers); +// Returns: [1, 1, 3, 4, 5, 9] + // 按单个属性排序 const users = [ { name: 'john', age: 30 }, @@ -55,23 +75,20 @@ const products = [ const sorted = sortBy(products, [ 'category', - item => -item.price, // 价格按降序排序 + item => -item.price, // 价格按降序排序(负数转换) ]); // Returns: 先按类别排序,然后按价格从高到低排序 // 按计算值排序 const words = ['hello', 'a', 'wonderful', 'world']; -const byLength = sortBy( - words.map(word => ({ word, length: word.length })), - ['length'] -); -// Returns: 按字符串长度排序的对象数组 +const byLength = sortBy(words, [word => word.length]); +// Returns: ['a', 'hello', 'world', 'wonderful'] ``` #### 参数 -- `arr` (`readonly T[]`): 要排序的对象数组。 -- `criteria` (`Array<((item: T) => unknown) | keyof T>`): 排序标准。可以是对象属性名或转换函数的数组,前面的标准优先级更高。 +- `arr` (`readonly T[]`): 要排序的数组。 +- `criteria` (`Array<((item: T) => unknown) | keyof T>`, 可选): 排序标准。可以是对象属性名或转换函数的数组,前面的标准优先级更高。如果未提供或为空数组,则按原始类型的值本身排序。 #### 返回值 diff --git a/src/array/orderBy.spec.ts b/src/array/orderBy.spec.ts index 15cd06f9a..b18331f8d 100644 --- a/src/array/orderBy.spec.ts +++ b/src/array/orderBy.spec.ts @@ -60,4 +60,49 @@ describe('orderBy', () => { { user: 'fred', age: 48 }, ]); }); + + it('should order strings in ascending order', () => { + const strings = ['banana', 'apple', 'cherry']; + expect(orderBy(strings, [x => x], ['asc'])).toEqual(['apple', 'banana', 'cherry']); + }); + + it('should order strings in descending order', () => { + const strings = ['banana', 'apple', 'cherry']; + expect(orderBy(strings, [x => x], ['desc'])).toEqual(['cherry', 'banana', 'apple']); + }); + + it('should order numbers', () => { + const numbers = [3, 1, 4, 1, 5]; + expect(orderBy(numbers, [x => x], ['desc'])).toEqual([5, 4, 3, 1, 1]); + }); + + it('should order strings by multiple criteria', () => { + const strings = ['apple', 'banana', 'cherry']; + expect(orderBy(strings, [x => x.length, x => x], ['asc', 'desc'])).toEqual(['apple', 'cherry', 'banana']); + }); + + it('should order strings without criteria in ascending order', () => { + const strings = ['banana', 'apple', 'cherry']; + expect(orderBy(strings, [], ['asc'])).toEqual(['apple', 'banana', 'cherry']); + }); + + it('should order strings without criteria in descending order', () => { + const strings = ['banana', 'apple', 'cherry']; + expect(orderBy(strings, [], ['desc'])).toEqual(['cherry', 'banana', 'apple']); + }); + + it('should order numbers without criteria', () => { + const numbers = [3, 1, 4, 1, 5]; + expect(orderBy(numbers, [], ['desc'])).toEqual([5, 4, 3, 1, 1]); + }); + + it('should order primitives with default parameters', () => { + const numbers = [3, 1, 4, 1, 5]; + expect(orderBy(numbers)).toEqual([1, 1, 3, 4, 5]); + }); + + it('should order strings with only order specified', () => { + const strings = ['banana', 'apple', 'cherry']; + expect(orderBy(strings, [], ['desc'])).toEqual(['cherry', 'banana', 'apple']); + }); }); diff --git a/src/array/orderBy.ts b/src/array/orderBy.ts index a92675a8a..f417cb733 100644 --- a/src/array/orderBy.ts +++ b/src/array/orderBy.ts @@ -1,19 +1,21 @@ import { compareValues } from '../_internal/compareValues.ts'; /** - * Sorts an array of objects based on the given `criteria` and their corresponding order directions. + * Sorts an array of objects or primitives based on the given `criteria` and their corresponding order directions. * - * - If you provide keys, it sorts the objects by the values of those keys. - * - If you provide functions, it sorts based on the values returned by those functions. + * - For objects: If you provide keys, it sorts the objects by the values of those keys. + * - For objects: If you provide functions, it sorts based on the values returned by those functions. + * - For primitives: If you provide functions, it sorts based on the values returned by those functions. + * - For primitives: If you provide no criteria, it sorts the primitives themselves. * * The function returns the array of objects sorted in corresponding order directions. * If two objects have the same value for the current criterion, it uses the next criterion to determine their order. * If the number of orders is less than the number of criteria, it uses the last order for the rest of the criteria. * * @template T - The type of elements in the array. - * @param {T[]} arr - The array of objects to be sorted. - * @param {Array<((item: T) => unknown) | keyof T>} criteria - The criteria for sorting. This can be an array of object keys or functions that return values used for sorting. - * @param {Array<'asc' | 'desc'>} orders - An array of order directions ('asc' for ascending or 'desc' for descending). + * @param {T[]} arr - The array of objects or primitives to be sorted. + * @param {Array<((item: T) => unknown) | keyof T>} [criteria=[]] - The criteria for sorting. This can be an array of object keys or functions that return values used for sorting. If empty or not provided, sorts by the values themselves. + * @param {Array<'asc' | 'desc'>} [orders=['asc']] - An array of order directions ('asc' for ascending or 'desc' for descending). * @returns {T[]} - The sorted array. * * @example @@ -33,22 +35,37 @@ import { compareValues } from '../_internal/compareValues.ts'; * // { user: 'fred', age: 48 }, * // { user: 'fred', age: 40 }, * // ] + * + * @example + * // Sort an array of strings in descending order. + * const strings = ['banana', 'apple', 'cherry']; + * const result = orderBy(strings, [], ['desc']); + * // result will be: ['cherry', 'banana', 'apple'] + * + * @example + * // Sort an array of numbers in ascending order (default). + * const numbers = [3, 1, 2]; + * const result = orderBy(numbers); + * // result will be: [1, 2, 3] */ -export function orderBy( +export function orderBy( arr: readonly T[], - criteria: Array<((item: T) => unknown) | keyof T>, - orders: Array<'asc' | 'desc'> + criteria: Array<((item: T) => unknown) | keyof T> = [], + orders: Array<'asc' | 'desc'> = ['asc'] ): T[] { + const effectiveCriteria = criteria.length > 0 ? criteria : [(item: T) => item]; + const effectiveOrders = orders.length > 0 ? orders : ['asc' as const]; + return arr.slice().sort((a, b) => { - const ordersLength = orders.length; + const ordersLength = effectiveOrders.length; - for (let i = 0; i < criteria.length; i++) { - const order = ordersLength > i ? orders[i] : orders[ordersLength - 1]; - const criterion = criteria[i]; + for (let i = 0; i < effectiveCriteria.length; i++) { + const order = ordersLength > i ? effectiveOrders[i] : effectiveOrders[ordersLength - 1]; + const criterion = effectiveCriteria[i]; const criterionIsFunction = typeof criterion === 'function'; - const valueA = criterionIsFunction ? criterion(a) : a[criterion]; - const valueB = criterionIsFunction ? criterion(b) : b[criterion]; + const valueA = criterionIsFunction ? criterion(a) : a[criterion as keyof T]; + const valueB = criterionIsFunction ? criterion(b) : b[criterion as keyof T]; const result = compareValues(valueA, valueB, order); diff --git a/src/array/sortBy.spec.ts b/src/array/sortBy.spec.ts index 06944d3de..17c4a9776 100644 --- a/src/array/sortBy.spec.ts +++ b/src/array/sortBy.spec.ts @@ -53,4 +53,34 @@ describe('sortBy', () => { { user: 'foo', age: 24 }, ]); }); + + it('should sort strings with criteria', () => { + const strings = ['banana', 'apple', 'cherry']; + expect(sortBy(strings, [x => x])).toEqual(['apple', 'banana', 'cherry']); + }); + + it('should sort numbers with criteria', () => { + const numbers = [3, 1, 4, 1, 5]; + expect(sortBy(numbers, [x => x])).toEqual([1, 1, 3, 4, 5]); + }); + + it('should sort strings by length', () => { + const strings = ['apple', 'banana', 'cherry']; + expect(sortBy(strings, [x => x.length, x => x])).toEqual(['apple', 'banana', 'cherry']); + }); + + it('should sort strings without criteria', () => { + const strings = ['banana', 'apple', 'cherry']; + expect(sortBy(strings)).toEqual(['apple', 'banana', 'cherry']); + }); + + it('should sort numbers without criteria', () => { + const numbers = [3, 1, 4, 1, 5]; + expect(sortBy(numbers)).toEqual([1, 1, 3, 4, 5]); + }); + + it('should sort strings with empty criteria array', () => { + const strings = ['banana', 'apple', 'cherry']; + expect(sortBy(strings, [])).toEqual(['apple', 'banana', 'cherry']); + }); }); diff --git a/src/array/sortBy.ts b/src/array/sortBy.ts index ddf20f20c..1af7b5bd7 100644 --- a/src/array/sortBy.ts +++ b/src/array/sortBy.ts @@ -1,17 +1,19 @@ import { orderBy } from './orderBy.ts'; /** - * Sorts an array of objects based on the given `criteria`. + * Sorts an array of objects or primitives based on the given `criteria`. * - * - If you provide keys, it sorts the objects by the values of those keys. - * - If you provide functions, it sorts based on the values returned by those functions. + * - For objects: If you provide keys, it sorts the objects by the values of those keys. + * - For objects: If you provide functions, it sorts based on the values returned by those functions. + * - For primitives: If you provide functions, it sorts based on the values returned by those functions. + * - For primitives: If you provide no criteria, it sorts the primitives themselves. * * The function returns the array of objects sorted in ascending order. * If two objects have the same value for the current criterion, it uses the next criterion to determine their order. * * @template T - The type of the objects in the array. - * @param {T[]} arr - The array of objects to be sorted. - * @param {Array<((item: T) => unknown) | keyof T>} criteria - The criteria for sorting. This can be an array of object keys or functions that return values used for sorting. + * @param {T[]} arr - The array of objects or primitives to be sorted. + * @param {Array<((item: T) => unknown) | keyof T>} [criteria=[]] - The criteria for sorting. This can be an array of object keys or functions that return values used for sorting. If empty or not provided, sorts by the values themselves. * @returns {T[]} - The sorted array. * * @example @@ -31,7 +33,24 @@ import { orderBy } from './orderBy.ts'; * // { user : 'foo', age: 8 }, * // { user : 'foo', age: 24 }, * // ] + * + * @example + * // Sort an array of strings (no criteria needed for primitives) + * const strings = ['banana', 'apple', 'cherry']; + * sortBy(strings); + * // result will be: ['apple', 'banana', 'cherry'] + * + * @example + * // Sort strings by length + * sortBy(strings, [x => x.length]); + * // result will be: ['apple', 'banana', 'cherry'] + * + * @example + * // Sort strings case-insensitively + * const mixed = ['Banana', 'apple', 'Cherry']; + * sortBy(mixed, [x => x.toLowerCase()]); + * // result will be: ['apple', 'Banana', 'Cherry'] */ -export function sortBy(arr: readonly T[], criteria: Array<((item: T) => unknown) | keyof T>): T[] { +export function sortBy(arr: readonly T[], criteria: Array<((item: T) => unknown) | keyof T> = []): T[] { return orderBy(arr, criteria, ['asc']); }