You can find all the code in this post at repo Github.
Array related challenges
ArrayOf
/** * @return {Array} */ function arrayOf(arr) { return [].slice.call(arguments); } // Usage example const array1 = [1, 2, 3]; const array2 = [4, 5, 6]; const combinedArray = arrayOf(array1, array2); console.log(combinedArray); // => [ [ 1, 2, 3 ], [ 4, 5, 6 ] ]
Array to tree
/** * @param {Array} arr * @return {Array} */ function arrToTree(arr) { const tree = []; const hashmap = new Map(); // create nodes and store references arr.forEach((item) => { hashmap[item.id] = { id: item.id, name: item.name, children: [], }; }); // build the tree arr.forEach((item) => { if (item.parentId === null) { tree.push(hashmap[item.id]); } else { hashmap[item.parentId].children.push(hashmap[item.id]); } }); return tree; } // Usage example const flatArray = [ { id: 1, name: "Node 1", parentId: null }, { id: 2, name: "Node 1.1", parentId: 1 }, { id: 3, name: "Node 1.2", parentId: 1 }, { id: 4, name: "Node 1.1.1", parentId: 2 }, { id: 5, name: "Node 2", parentId: null }, { id: 6, name: "Node 2.1", parentId: 5 }, { id: 7, name: "Node 2.2", parentId: 5 }, ]; const tree = arrToTree(flatArray); console.log(tree); // => [{ id: 1, name: 'Node 1', children: [ [Object], [Object] ] }, { id: 5, name: 'Node 2', children: [ [Object], [Object] ] }]
Array wrapper
class ArrayWrapper { constructor(arr) { this._arr = arr; } valueOf() { return this._arr.reduce((sum, num) => sum + num, 0); } toString() { return `[${this._arr.join(",")}]`; } } // Usage example const obj1 = new ArrayWrapper([1, 2]); const obj2 = new ArrayWrapper([3, 4]); console.log(obj1 + obj2); // => 10 console.log(String(obj1)); // => [1,2]
Array-like to Array
/** * @param {any} arrayLike * @return {Array} */ function arrayLikeToArray(arrayLike) { return Array.from(arrayLike); } // Usage example const arrayLike = { 0: "a", 1: "b", 2: "c", length: 3, }; console.log(arrayLikeToArray(arrayLike)); // => ['a', 'b', 'c']
Chunk
/** * @template T * @param {Array<t>} arr The array to process. * @param {number} [size=1] The length of each chunk. * @returns {Array<array>>} The new array of chunks. */ function chunk(arr, size = 1) { if (!Array.isArray(arr) || size [['a'], ['b'], ['c'], ['d']] console.log(chunk([1, 2, 3, 4], 2)); // => [[1, 2], [3, 4]] console.log(chunk([1, 2, 3, 4], 3)); // => [[1, 2, 3], [4]] </array></t>
Combinations
/** * @param {array} arrs * @return {array} */ function generateCombinations(arrs) { const result = []; function backtrack(start, current) { if (start === arrs.length) { result.push(current.join('')); return; } for (const item of arrs[start]) { current.push(item); backtrack(start + 1, current); current.pop(); } } backtrack(0, []); return result; } // Usage example const nestedArray = [['a', 'b'], [1, 2], [3, 4]]; console.log(generateCombinations(nestedArray)); // => ['a13', 'a14', 'a23', 'a24', 'b13', 'b14', 'b23', 'b24']
Difference
/** * @param {Array} array * @param {Array} values * @return {Array} */ function difference(arr, values) { const newArray = []; const valueSet = new Set(values); for (let i = 0; i [1] console.log(difference([1, 2, 3, 4], [2, 3, 1])); // => [4] console.log(difference([1, 2, 3], [2, 3, 1, 4])); // => [] console.log(difference([1, , 3], [1])); // => [3]
Drop right while
/** * @param {Array} array * @param {Function} predicate * @return {Array} */ function dropRightWhile(arr, predicate) { let index = arr.length - 1; while (index >= 0 && predicate(arr[index], index, arr)) { index -= 1; } return arr.slice(0, index + 1); } // Usage example console.log(dropRightWhile([1, 2, 3, 4, 5], (value) => value > 3)); // => [1, 2, 3] console.log(dropRightWhile([1, 2, 3], (value) => value [] console.log(dropRightWhile([1, 2, 3, 4, 5], (value) => value > 6)); // => [1, 2, 3, 4, 5]
Drop while
/** * @param {Array} array * @param {Function} predicate * @return {Array} */ function dropWhile(arr, predicate) { let index = 0; while (index value [3, 4, 5] dropWhile([1, 2, 3], (value) => value []
Flatten
/** * @param {Array} value * @return {Array} */ function flatten(arr) { const newArray = []; const copy = [...arr]; while (copy.length) { const item = copy.shift(); if (Array.isArray(item)) { copy.unshift(...item); } else { newArray.push(item); } } return newArray; } // Usage example console.log(flatten([1, 2, 3])); // [1, 2, 3] // Inner arrays are flattened into a single level. console.log(flatten([1, [2, 3]])); // [1, 2, 3] console.log( flatten([ [1, 2], [3, 4], ]) ); // [1, 2, 3, 4] // Flattens recursively. console.log(flatten([1, [2, [3, [4, [5]]]]])); // [1, 2, 3, 4, 5]
Generate unique random array
/** * @param {number} range * @param {number} outputCount * @return {Array} */ function generateUniqueRandomArray(range, outputCount) { const arr = Array.from({ length: range }, (_, i) => i + 1); const result = []; for (let i = 0; i [3, 7, 1, 9, 5]
Intersection By
/** * @param {Function} iteratee * @param {Array[]} arrays * @returns {Array} */ function intersectionBy(iteratee, ...arrs) { if (!arrs.length) { return []; } const mappedArrs = arrs.map((arr) => arr.map(iteratee)); let intersectedValues = mappedArrs[0].filter((value) => { return mappedArrs.every((mappedArr) => mappedArr.includes(value)); }); intersectedValues = intersectedValues.filter((value, index, self) => { return self.indexOf(value) === index; }); return intersectedValues.map((value) => { const index = mappedArrs[0].indexOf(value); return arrs[0][index]; }); } // Usage example const result = intersectionBy(Math.floor, [1.2, 2.4], [2.5, 3.6]); // => [2.4] console.log(result); // => [2.4] const result2 = intersectionBy( (str) => str.toLowerCase(), ["apple", "banana", "ORANGE", "orange"], ["Apple", "Banana", "Orange"] ); console.log(result2); // => ['apple', 'banana', 'ORANGE']
Intersection
/** * @param {Array<unknown>[]} arrays - The arrays to find the intersection of. * @returns {Array<unknown>} - An array containing the elements common to all input arrays. */ function intersectArrays(...arrs) { if (!arrs.length) { return []; } const set = new Set(arrs[0]); for (let i = 1; i { if (!arrs[i].includes(value)) { set.delete(value); } }); } return Array.from(set); } // Usage example console.log(intersectArrays([1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 6])); // => [3, 4] </unknown></unknown>
Mean
/** * @param {Array} array * @return {Number} */ function mean(arr) { return arr.reduce((sum, number) => sum + number, 0) / arr.length; } // Usage example console.log(mean([1, 2, 3])); // => 2 console.log(mean([1, 2, 3, 4, 5])); // => 3
Remove duplicates
/** * @param {*} arr */ function removeDuplicates(arr) { return Array.from(new Set(arr)); } // Usage example const inputArray = [1, 2, 3, 2, 1, 4, 5, 6, 5, 4]; const outputArray = removeDuplicates(inputArray); console.log(outputArray); // => [1, 2, 3, 4, 5, 6]
Shuffle
/** * @param {any[]} arr * @returns {void} */ function shuffle(arr) { if (arr.length [*, *, *, *]
SortBy
/** * @param {Array} arr * @param {Function} fn * @return {Array} */ function sortBy(arr, fn) { return arr.sort((a, b) => fn(a) - fn(b)); } // Usage example console.log(sortBy([5, 4, 1, 2, 3], (x) => x)); // => [1, 2, 3, 4, 5]
Tree to array
/** * @param {Array} tree * @param {number} parentId * @return {Array} */ function treeToArr(tree, parentId = null) { const arr = []; tree.forEach((node) => { const { id, name } = node; arr.push({ id, name, parentId }); // recursive if (node.children && node.children.length > 0) { arr.push(...treeToArr(node.children, id)); } }); return arr; } // Usage example const tree = [ { id: 1, name: "Node 1", children: [ { id: 2, name: "Node 1.1", children: [ { id: 4, name: "Node 1.1.1", children: [], }, ], }, { id: 3, name: "Node 1.2", children: [], }, ], }, { id: 5, name: "Node 2", children: [ { id: 6, name: "Node 2.1", children: [], }, { id: 7, name: "Node 2.2", children: [], }, ], }, ]; const flatArray = treeToArr(tree); console.log(flatArray); /* [ { id: 1, name: 'Node 1', parentId: null }, { id: 2, name: 'Node 1.1', parentId: 1 }, { id: 4, name: 'Node 1.1.1', parentId: 2 }, { id: 3, name: 'Node 1.2', parentId: 1 }, { id: 5, name: 'Node 2', parentId: null }, { id: 6, name: 'Node 2.1', parentId: 5 }, { id: 7, name: 'Node 2.2', parentId: 5 } ] */
Reference
- 2695. Array Wrapper - LeetCode
- 2677. Chunk Array - LeetCode
- 2724. Sort By - LeetCode
- 2625. Flatten Deeply Nested Array - LeetCode
- 131. implement _.chunk() - BFE.dev
- 8. can you shuffle() an array? - BFE.dev
- 384. Shuffle an Array - LeetCode
- 138. Intersection of two sorted arrays - BFE.dev
- 167. Intersection of unsorted arrays - BFE.dev
- 66. remove duplicates from an array - BFE.dev
The above is the detailed content of Array - JavaScript Challenges. For more information, please follow other related articles on the PHP Chinese website!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1
Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.
