GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — algorithm-practice/javascript/4_array-programs/splitArray.js at main · amit265/algorithm-practice Expand file tree/ Copy pathsplitArray.jsMore file actions executable file ·84 lines (61 loc) · 1.62 KB / Copy pathsplitArray.jsFile metadata and controlsexecutable file ·84 lines (61 loc) · 1.62 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 // 27. Split an Array into Chunks // 1. Using slice() Method { let a = [10, 20, 30, 40, 50, 60, 70]; let chunk = 4; let a1 = a.slice(0, chunk); let a2 = a.slice(chunk, chunk + a.length); console.log("Array 1 :" + a1 + "\nArray 2: " + a2); } // 2. Using splice() Method { let a = [10, 20, 30, 40, 50, 60, 70, 80]; let chunk = 2; // Spliced arrays into 4 chunks let a1 = a.splice(0, chunk); let a2 = a.splice(0, chunk); let a3 = a.splice(0, chunk); let a4 = a.splice(0, chunk); // Display Output console.log("Array 1:", a1); console.log("Array 2:", a2); console.log("Array 3:", a3); console.log("Array 4:", a4); } // 4. Using JavaScript for Loop { // Given array let a = [10, 20, 30, 40, 50, 60, 70, 80]; // Size of chunk let chunkSize = 2; // Initialize the output array let chunks = []; // Loop to split array into chunks for (let i = 0; i < a.length; i += chunkSize) { let chunk = []; // Iterate for the size of chunk for (let j = i; j < i + chunkSize && j < a.length; j++) { chunk.push(a[j]); } // push the chunk to output array chunks.push(chunk); } // Display Output console.log("Chunks:", chunks); } // 5. Using reduce() with slice() Method { // Given array let a = [10, 20, 30, 40, 50, 60, 70, 80]; // Size of chunk let chunkSize = 2; // Split the array into chunks using reduce let chunks = a.reduce((acc, _, index) => { // Create chunk using array.slice() // and push into the accumulator acc.push(a.slice(index, index + chunkSize)); return acc; }, []); // Display Output console.log("Chunks:", chunks); } |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |