JavaScript-ലെ Array Iteration രീതികൾ (Methods)

ഡാറ്റ കൈകാര്യം ചെയ്യാൻ JavaScript arrays ധാരാളം ടൂളുകൾ വാഗ്ദാനം ചെയ്യുന്നു. വൃത്തിയുള്ള കോഡ് (clean code) എഴുതാൻ ഈ രീതികൾ നിങ്ങൾ അറിഞ്ഞിരിക്കണം.

  • forEach() ഓരോ എലമെന്റിനും വേണ്ടി ഒരു ഫംഗ്ഷൻ പ്രവർത്തിപ്പിക്കുന്നു. let nums = [10, 20, 30]; nums.forEach(num => console.log(num));

  • map() ഓരോ എലമെന്റിനെയും മാറ്റിമറിച്ചുകൊണ്ട് (transform) ഒരു പുതിയ array നിർമ്മിക്കുന്നു. let nums = [1, 2, 3]; let result = nums.map(num => num * 2); // [2, 4, 6]

  • flatMap() ഓരോ എലമെന്റിനെയും മാപ്പ് ചെയ്ത ശേഷം അതിന്റെ ഫലം ഫ്ലാറ്റൻ (flatten) ചെയ്യുന്നു. let arr = [1, 2, 3]; let result = arr.flatMap(num => [num, num * 2]); // [1, 2, 2, 4, 3, 6]

  • filter() ഒരു നിശ്ചിത പരിശോധനയിലൂടെ (test) വിജയിക്കുന്ന എലമെന്റുകൾ ഉപയോഗിച്ച് ഒരു പുതിയ array നിർമ്മിക്കുന്നു. let nums = [10, 20, 30, 40]; let result = nums.filter(num => num > 20); // [30, 40]

  • reduce() എല്ലാ എലമെന്റുകളെയും കൂട്ടി യോജിപ്പിച്ച് ഒരു ഒറ്റ മൂല്യമാക്കി (single value) മാറ്റുന്നു. let nums = [10, 20, 30]; let result = nums.reduce((total, num) => total + num, 0); // 60

  • reduceRight() reduce പോലെ തന്നെ പ്രവർത്തിക്കുന്നു, എന്നാൽ array-യുടെ അവസാനം മുതൽ തുടങ്ങുന്നു. let arr = ["A", "B", "C"]; let result = arr.reduceRight((acc, value) => acc + value); // CBA

  • every() എല്ലാ എലമെന്റുകളും ഒരു പരിശോധന വിജയിച്ചാൽ true എന്ന് നൽകുന്നു. let nums = [10, 20, 30]; let result = nums.every(num => num > 5); // true

  • some() കുറഞ്ഞത് ഒരു എലമെന്റ് എങ്കിലും പരിശോധന വിജയിച്ചാൽ true എന്ന് നൽകുന്നു. let nums = [10, 20, 30]; let result = nums.some(num => num > 25); // true

  • from() ഒരു iterable object-ൽ നിന്ന് ഒരു array നിർമ്മിക്കുന്നു. let result = Array.from("Hello"); // ['H', 'e', 'l', 'l', 'o']

  • keys() array-യിലെ കീകൾ (keys) അടങ്ങിയ ഒരു iterator നൽകുന്നു. let fruits = ["Apple", "Mango", "Orange"]; let result = fruits.keys(); // 0, 1, 2

  • entries() കീയും വാല്യൂവും (key and value) ജോഡികളായി അടങ്ങിയ ഒരു iterator നൽകുന്നു. let fruits = ["Apple", "Mango", "Orange"]; let result = fruits.entries(); // [0, 'Apple'], [1, 'Mango']...

  • with() ഒരു എലമെന്റ് മാറ്റം വരുത്തിയ പുതിയൊരു array നൽകുന്നു. let fruits = ["Apple", "Mango", "Orange"]; let result = fruits.with(1, "Grapes"); // ['Apple', 'Grapes', 'Orange']

  • Spread (...) ഒരു array-യിലെ എലമെന്റുകളെ വികസിപ്പിക്കുന്നു (expands). let arr1 = [1, 2]; let arr2 = [3, 4]; let result = [...arr1, ...arr2]; // [1, 2, 3, 4]

  • Rest (...) ഒന്നിലധികം എലമെന്റുകളെ ഒരു array-യിലേക്ക് ശേഖരിക്കുന്നു. function showNumbers(...nums) { console.log(nums); } showNumbers(10, 20, 30); // [10, 20, 30]

ഉറവിടം: https://dev.to/ezhil_abinayak_e38eec8fb/array-iteration-methods-in-javascript-20mc