New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@plq/array-functions

Package Overview
Dependencies
Maintainers
1
Versions
6
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@plq/array-functions - npm Package Compare versions

Comparing version 1.3.0 to 1.4.0

103

lib/index.d.ts

@@ -6,15 +6,118 @@ export type Sortable<T> = {

export type SortableOrder = 'asc' | 'desc';
/**
* Filters an array of objects so that the value of a given key occurs only once in the array.
* @template T The type of the object.
* @param {T} value The current value.
* @param {number} index The index of the current value.
* @param {T[]} array The array of objects.
* @param {keyof T} key The key to filter by.
* @returns {boolean} Whether the value is the first occurrence of the key's value in the array.
*
* @example
* const array = [{ id: 1 }, { id: 2 }, { id: 1 }];
* const filtered = array.filter((value, index, array) => filterBySameKeyValue(value, index, array, 'id'));
* // filtered: [{ id: 1 }, { id: 2 }]
*/
export declare function filterBySameKeyValue<T extends {
[k in string]: unknown;
}>(value: T, index: number, array: T[], key: keyof T): boolean;
/**
* Compares two values.
* @param {string | number} a The first value.
* @param {string | number} b The second value.
* @param {SortableOrder} [order='desc'] The order of sorting.
* @returns {number} The result of the comparison.
*
* This function compares two values `a` and `b`. Depending on the type of these values, the function uses different comparison approaches:
* - If the values are strings, the function uses the `localeCompare` method, which compares strings based on locale. This means that the strings are compared according to the sorting rules for the current language and region.
* - If the values are numbers, the function simply subtracts one number from another. This gives a negative number if `a` is less than `b`, a positive number if `a` is greater than `b`, and zero if `a` and `b` are equal.
* - If the values are of any other type, the function returns `0`.
*
* The function also takes into account the sorting order, which can be either 'asc' (ascending) or 'desc' (descending). If the sorting order is 'asc', the function returns the comparison result as is. If the sorting order is 'desc', the function returns the reverse comparison result.
*
* @example
* ['a', 'b'].sort((a, b) => compareValues(a, b, 'asc')); // Output: ['b', 'a']
*/
export declare function compareValues<T extends (string | number)>(a: T, b: T, order?: SortableOrder): number;
/**
* Sorts an array of objects by a given key.
* @template T The type of the object.
* @param {T[]} items The array of objects.
* @param {SortableKey<T>} key The key to sort by.
* @param {SortableOrder} [order='desc'] The order of sorting.
* @returns {T[]} The sorted array.
*
* @example
* sortBy([{ id: 2 }, { id: 1 }], 'id', 'asc'); // Output: [{ id: 1 }, { id: 2 }]
*/
export declare function sortBy<T extends Sortable<T>>(items: T[], key: SortableKey<T>, order?: SortableOrder): T[];
/**
* Checks if an array of values is sorted.
* @template T The type of the values.
* @param {T[]} values The array of values.
* @param {SortableOrder} [order='desc'] The order of sorting.
* @returns {boolean} Whether the array is sorted.
*
* @example
* isSortedValues([1, 2, 3], 'asc'); // Output: true
*/
export declare function isSortedValues<T extends (string | number)>(values: T[], order?: SortableOrder): boolean;
/**
* Checks if an array of objects is sorted by a given key.
* @template T The type of the object.
* @param {T[]} array The array of objects.
* @param {SortableKey<T>} key The key to check by.
* @param {SortableOrder} [order='desc'] The order of sorting.
* @returns {boolean} Whether the array is sorted by the key.
*
* @example
* isSortedBy([{ id: 1 }, { id: 2 }], 'id', 'asc'); // Output: true
*/
export declare function isSortedBy<T extends Sortable<T>>(array: T[], key: SortableKey<T>, order?: SortableOrder): boolean;
/**
* Returns the array of values of a given key from an array of objects.
* @template T The type of the object.
* @param {T[]} arr The array of objects.
* @param {keyof T} key The key to get values by.
* @returns {T[keyof T][]} The array of values.
*
* @example
* const array = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }];
* getKeyValue(array, 'name'); // Output: ['Alice', 'Bob']
*/
export declare function getKeyValue<T extends {
[k in string]: unknown;
}>(arr: T[], key: keyof T): T[keyof T][];
/**
* Returns an array of unique values from an array of objects.
* @template T The type of the object.
* @param {T[]} arr The array of objects.
* @param {keyof T} key The key to get unique values by.
* @returns {T[keyof T][]} The array of unique values.
*
* @example
* const array = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Alice' }];
* getUniqueValues(array, 'name'); // Output: ['Alice']
*/
export declare function getUniqueValues<T extends {
[k in string]: unknown;
}>(arr: T[], key: keyof T): T[keyof T][];
/**
* Splits an array of objects into subarrays with the same value of the given key.
* @template T The type of the object.
* @param {T[]} arr The array of objects.
* @param {keyof T} key The key to split by.
* @returns {T[][]} An array of subarrays, where each subarray contains objects with the same value for the given key.
*
* @example
* const array = [
* { id: 1, name: 'Alice' },
* { id: 2, name: 'Bob' },
* { id: 3, name: 'Alice' },
* ];
* splitByKeyValue(array, 'name'); // Output: [[{ id: 1, name: 'Alice' }, { id: 3, name: 'Alice' }], [{ id: 2, name: 'Bob' }]]
*/
export declare function splitByKeyValue<T extends {
[k in string]: unknown;
}>(arr: T[], key: keyof T): T[][];
//# sourceMappingURL=index.d.ts.map

124

lib/index.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getUniqueValues = exports.getKeyValue = exports.isSortedBy = exports.isSortedValues = exports.sortBy = exports.compareValues = exports.filterBySameKeyValue = void 0;
exports.splitByKeyValue = exports.getUniqueValues = exports.getKeyValue = exports.isSortedBy = exports.isSortedValues = exports.sortBy = exports.compareValues = exports.filterBySameKeyValue = void 0;
const is_1 = require("@plq/is");
const defaultOrder = 'desc';
/**
* Filters an array of objects so that the value of a given key occurs only once in the array.
* @template T The type of the object.
* @param {T} value The current value.
* @param {number} index The index of the current value.
* @param {T[]} array The array of objects.
* @param {keyof T} key The key to filter by.
* @returns {boolean} Whether the value is the first occurrence of the key's value in the array.
*
* @example
* const array = [{ id: 1 }, { id: 2 }, { id: 1 }];
* const filtered = array.filter((value, index, array) => filterBySameKeyValue(value, index, array, 'id'));
* // filtered: [{ id: 1 }, { id: 2 }]
*/
function filterBySameKeyValue(value, index, array, key) {

@@ -10,4 +24,22 @@ return index === array.findIndex(v => v[key] === value[key]);

exports.filterBySameKeyValue = filterBySameKeyValue;
/**
* Compares two values.
* @param {string | number} a The first value.
* @param {string | number} b The second value.
* @param {SortableOrder} [order='desc'] The order of sorting.
* @returns {number} The result of the comparison.
*
* This function compares two values `a` and `b`. Depending on the type of these values, the function uses different comparison approaches:
* - If the values are strings, the function uses the `localeCompare` method, which compares strings based on locale. This means that the strings are compared according to the sorting rules for the current language and region.
* - If the values are numbers, the function simply subtracts one number from another. This gives a negative number if `a` is less than `b`, a positive number if `a` is greater than `b`, and zero if `a` and `b` are equal.
* - If the values are of any other type, the function returns `0`.
*
* The function also takes into account the sorting order, which can be either 'asc' (ascending) or 'desc' (descending). If the sorting order is 'asc', the function returns the comparison result as is. If the sorting order is 'desc', the function returns the reverse comparison result.
*
* @example
* ['a', 'b'].sort((a, b) => compareValues(a, b, 'asc')); // Output: ['b', 'a']
*/
function compareValues(a, b, order = defaultOrder) {
switch (typeof a) {
const type = typeof a;
switch (type) {
case 'string':

@@ -26,2 +58,13 @@ return order === 'asc'

exports.compareValues = compareValues;
/**
* Sorts an array of objects by a given key.
* @template T The type of the object.
* @param {T[]} items The array of objects.
* @param {SortableKey<T>} key The key to sort by.
* @param {SortableOrder} [order='desc'] The order of sorting.
* @returns {T[]} The sorted array.
*
* @example
* sortBy([{ id: 2 }, { id: 1 }], 'id', 'asc'); // Output: [{ id: 1 }, { id: 2 }]
*/
function sortBy(items, key, order = defaultOrder) {

@@ -43,2 +86,12 @@ if (items.length <= 1)

exports.sortBy = sortBy;
/**
* Checks if an array of values is sorted.
* @template T The type of the values.
* @param {T[]} values The array of values.
* @param {SortableOrder} [order='desc'] The order of sorting.
* @returns {boolean} Whether the array is sorted.
*
* @example
* isSortedValues([1, 2, 3], 'asc'); // Output: true
*/
function isSortedValues(values, order = defaultOrder) {

@@ -51,3 +104,3 @@ if (values.length === 0)

if (typeof value !== typeof valuesArray[index - 1])
throw new Error(`Types are not equal (a: ${typeof value}, b: ${typeof valuesArray[index - 1]})`);
throw new Error(`Types are not equal (${valuesArray[index - 1]}: ${typeof valuesArray[index - 1]}, ${value}: ${typeof value})`);
const prevValue = valuesArray[index - 1];

@@ -67,2 +120,13 @@ switch (typeof value) {

exports.isSortedValues = isSortedValues;
/**
* Checks if an array of objects is sorted by a given key.
* @template T The type of the object.
* @param {T[]} array The array of objects.
* @param {SortableKey<T>} key The key to check by.
* @param {SortableOrder} [order='desc'] The order of sorting.
* @returns {boolean} Whether the array is sorted by the key.
*
* @example
* isSortedBy([{ id: 1 }, { id: 2 }], 'id', 'asc'); // Output: true
*/
function isSortedBy(array, key, order = defaultOrder) {

@@ -85,2 +149,13 @@ if (array.length <= 1)

exports.isSortedBy = isSortedBy;
/**
* Returns the array of values of a given key from an array of objects.
* @template T The type of the object.
* @param {T[]} arr The array of objects.
* @param {keyof T} key The key to get values by.
* @returns {T[keyof T][]} The array of values.
*
* @example
* const array = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }];
* getKeyValue(array, 'name'); // Output: ['Alice', 'Bob']
*/
function getKeyValue(arr, key) {

@@ -90,7 +165,46 @@ return arr.map(item => item[key]);

exports.getKeyValue = getKeyValue;
/**
* Returns an array of unique values from an array of objects.
* @template T The type of the object.
* @param {T[]} arr The array of objects.
* @param {keyof T} key The key to get unique values by.
* @returns {T[keyof T][]} The array of unique values.
*
* @example
* const array = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Alice' }];
* getUniqueValues(array, 'name'); // Output: ['Alice']
*/
function getUniqueValues(arr, key) {
const filtered = arr.filter((item, index, array) => filterBySameKeyValue(item, index, array, key));
return getKeyValue(filtered, key);
const uniqueValues = new Set();
arr.forEach(item => uniqueValues.add(item[key]));
return Array.from(uniqueValues);
}
exports.getUniqueValues = getUniqueValues;
/**
* Splits an array of objects into subarrays with the same value of the given key.
* @template T The type of the object.
* @param {T[]} arr The array of objects.
* @param {keyof T} key The key to split by.
* @returns {T[][]} An array of subarrays, where each subarray contains objects with the same value for the given key.
*
* @example
* const array = [
* { id: 1, name: 'Alice' },
* { id: 2, name: 'Bob' },
* { id: 3, name: 'Alice' },
* ];
* splitByKeyValue(array, 'name'); // Output: [[{ id: 1, name: 'Alice' }, { id: 3, name: 'Alice' }], [{ id: 2, name: 'Bob' }]]
*/
function splitByKeyValue(arr, key) {
const groups = {};
arr.forEach(item => {
const keyValue = String(item[key]);
if (!groups[keyValue]) {
groups[keyValue] = [];
}
groups[keyValue].push(item);
});
return Object.values(groups);
}
exports.splitByKeyValue = splitByKeyValue;
//# sourceMappingURL=index.js.map

6

package.json
{
"name": "@plq/array-functions",
"version": "1.3.0",
"version": "1.4.0",
"description": "A set of frequently used functions for working with arrays, for sorting, filtering or checking the state of an array",

@@ -54,3 +54,3 @@ "main": "lib/index.js",

"devDependencies": {
"@release-it/conventional-changelog": "^7.0.2",
"@release-it/conventional-changelog": "^8.0.1",
"@types/jest": "^29.5.5",

@@ -61,3 +61,3 @@ "@typescript-eslint/eslint-plugin": "^6.7.4",

"jest": "^29.7.0",
"release-it": "^16.2.1",
"release-it": "^17.0.0",
"ts-jest": "^29.1.1",

@@ -64,0 +64,0 @@ "ts-node": "^10.9.1",

@@ -89,2 +89,18 @@ # array-functions

### `splitByKeyValue`
Splits an array of objects into subarrays with the same value of the given key.
```javascript
import { splitByKeyValue } from '@plq/array-functions'
const array = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Alice' },
]
console.log(splitByKeyValue(array, 'name')) // Output: [[{ id: 1, name: 'Alice' }, { id: 3, name: 'Alice' }], [{ id: 2, name: 'Bob' }]]
```
## Development

@@ -91,0 +107,0 @@

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc