Files
BarangaySystem/resources/js/utils/array.js
2026-06-06 18:43:00 +08:00

67 lines
1.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* Finds duplicate sub-arrays in a multidimensional array.
*
* @param {Array<Array>} arr - The multidimensional array to check
* @returns {Array<Array>|false} - Array of duplicates or false if none
*
* @example
* findDuplicatesInMultidimensionalArray([[1,2],[3,4],[1,2]])
* // returns [[1,2]]
*/
export function findDuplicatesInMultidimensionalArray(arr) {
const seen = new Set()
const duplicates = []
for (const subArr of arr) {
const key = JSON.stringify(subArr)
if (seen.has(key)) {
duplicates.push(subArr)
} else {
seen.add(key)
}
}
return duplicates.length ? duplicates : false
}
/**
* Joins array elements with a hyphen.
*
* @param {Array<string|number>} arr
* @returns {string}
*
* @example
* implodeArrayWithHyphen([1,2,3]) // "1-2-3"
*/
export function implodeArrayWithHyphen(arr) {
if (!Array.isArray(arr)) return ''
return arr.join('-')
}
/**
* Shuffles an array in-place using the FisherYates algorithm.
*
* @param {Array} array - The array to shuffle
* @returns {Array} The shuffled array
*
* @example
* shuffleArray([1,2,3,4])
* // might return [3,1,4,2]
*/
export function shuffleArray(array) {
if (!Array.isArray(array)) return []
let currentIndex = array.length
let randomIndex
while (currentIndex !== 0) {
randomIndex = Math.floor(Math.random() * currentIndex)
currentIndex--
;[array[currentIndex], array[randomIndex]] = [array[randomIndex], array[currentIndex]]
}
return array
}