Cookie Consent by Free Privacy Policy Generator ๐Ÿ“Œ The 20 Most Common Use Cases for JavaScript Arrays

๐Ÿ  Team IT Security News

TSecurity.de ist eine Online-Plattform, die sich auf die Bereitstellung von Informationen,alle 15 Minuten neuste Nachrichten, Bildungsressourcen und Dienstleistungen rund um das Thema IT-Sicherheit spezialisiert hat.
Ob es sich um aktuelle Nachrichten, Fachartikel, Blogbeitrรคge, Webinare, Tutorials, oder Tipps & Tricks handelt, TSecurity.de bietet seinen Nutzern einen umfassenden รœberblick รผber die wichtigsten Aspekte der IT-Sicherheit in einer sich stรคndig verรคndernden digitalen Welt.

16.12.2023 - TIP: Wer den Cookie Consent Banner akzeptiert, kann z.B. von Englisch nach Deutsch รผbersetzen, erst Englisch auswรคhlen dann wieder Deutsch!

Google Android Playstore Download Button fรผr Team IT Security



๐Ÿ“š The 20 Most Common Use Cases for JavaScript Arrays


๐Ÿ’ก Newskategorie: Programmierung
๐Ÿ”— Quelle: dev.to

Splice, slice, pop and shift. Is the array sort method stable and not in-place? It's not easy to remember all JavaScript array methods and what the difference between them are. They are all synonyms, as if they where taken directly from a thesaurus.

This array cheat sheet lists all the array methods you usually need in JavaScript, and the ones you don't need, is not here. Simple as that! To make it even easier for you, I have based the cheat sheet on common use cases.

JavaScript array methods meme
New challenge, try to list all array methods without forgetting one of them

Immutability

Before we begin, a notice about immutability. All functions used in this article are immutable, which shortly means, that you never mutate your original array when you use these methods. Immutability is very important in modern JavaScript, at least according to this Stack Overflow guy (and the rest of the Internet).

Even though each of these methods is immutable on their own, you are not totally safe against immutability. If you include mutable data types (arrays, objects, functions) in your immutable arrays, you can still mutate the mutable data within the array. We call such arrays to be shallowly immutable, in contrast to deeply immutable arrays which only includes immutable items.

Subscribe to my articles

Array Use Cases

  1. Add Element to Start of Array
  2. Add Element to End of Array
  3. Remove an Element From Start of Array
  4. Remove an Element From End of Array
  5. Insert Element at Index in Array
  6. Replace an Element at Index in Array
  7. Remove an Element at Index in Array
  8. Remove an Element By Value From an Array
  9. Remove Objects By Property From an Array
  10. Check if Array Includes an Element
  11. Check if Array Includes Object with Property
  12. Check if All Objects in an Array has a Property
  13. Convert Array to an Object
  14. Convert Array of Objects to an Object
  15. Convert Object to an Array
  16. Combine Two Arrays
  17. Sort an Array
  18. Sort an Array of Objects
  19. Reverse an Array
  20. Remove Duplicates From an Array

1. Add Element to Start of Array

To prepend an item to the beginning of an array, use array spreading.

const arr = [1, 2, 3];
const result = [0, ...arr];
console.log(result);
// [0, 1, 2, 3]

Do not use the unshift method, that will mutate the original array.

2. Add Element to End of Array

To append an item to the end of an array, use array spreading.

const arr = [1, 2, 3];
const result = [...arr, 4];
console.log(result);
// [1, 2, 3, 4]

Do not use the push method, that will mutate the original array.

3. Remove an Element From Start of Array

To remove the first item in an array, use slice method.

const arr = [1, 2, 3];
// Keep index 1 and everything after that.
const result = arr.slice(1);
console.log(result);
// [2, 3]

Do not use the shift or splice methods, they will mutate the original array.

4. Remove an Element From End of Array

To remove the last item in an array, use slice method.

const arr = [1, 2, 3];
// Keep index 0 and everything after that, except one element at the array.
const result = arr.slice(0, -1);
console.log(result);
// [1, 2]

Do not use the pop or splice methods, they will mutate the original array.

5. Insert Element at Index in Array

To add an item at a specific index of an array, use the toSpliced method.

const arr = [1, 2, 3];
// Keep index 1, delete 0 elements, add the element "one point five" and keep everything after that.
const result = arr.toSpliced(1, 0, "one point five");
console.log(result);
// [1, "one point five", 2, 3]

Do not use the splice method, that will mutate the original array.

6. Replace an Element at Index in Array

To replace an item from some index in an array, use the toSpliced or with method.

const arr = [1, 2, 3];

// Using toSpliced.
// Keep index 1, delete 1 elements, add the element "two" and keep everything after that.
const result1 = arr.toSpliced(1, 1, "two");
console.log(result1);
// [1, "two", 3]

// Using with.
// Copy the old array arr with index 1 replaced with "two".
const result2 = arr.with(1, "two");
console.log(result2);
// [1, "two", 3]

Do not use the splice method, that will mutate the original array.

7. Remove an Element at Index in Array

To remove an item from an array, use the toSpliced method.

const arr = [1, 2, 3];

// At index 1, delete 1 elements.
const result = arr.toSpliced(1, 1);
console.log(result);
// [1, 3]

Do not use the splice method, that will mutate the original array.

8. Remove an Element By Value From an Array

To remove a specific value from an array, use the filter method.

const arr = [1, 2, 3];
const result = arr.filter((element) => element !== 2);
console.log(result);
// [1, 3]

Do not use the indexOf together with splice method, that will mutate the original array.

9. Remove Objects By Property From an Array

To remove an object with a specific attribute from an array, use the filter method.

const arr = [{ num: 1 }, { num: 2 }, { num: 3 }];
const result = arr.filter((obj) => obj.num !== 2);
console.log(result);
// [{ num: 1 }, { num: 3 }]

Do not use the findIndex together with splice method, that will mutate the original array.

10. Check if Array Includes an Element

To check if an array contains a value, use includes method.

const arr = [1, 2, 3];
const result = arr.includes(2);
console.log(result);
// true

11. Check if Array Includes Object with Property

To check if an array contains an object with a property, use some method.

const arr = [{ num: 1 }, { num: 2 }, { num: 3 }];
const result = arr.some((obj) => obj.num === 2);
console.log(result);
// true

12. Check if All Objects in an Array has a Property

To check if every object in an array has a property, use every method.

const arr1 = [{ num: 1 }, { num: 2 }, { num: 3 }];
const result1 = arr1.every((obj) => obj.num === 2);
console.log(result1);
// false

const arr2 = [{ num: 2 }, { num: 2 }, { num: 2 }];
const result2 = arr2.every((obj) => obj.num === 2);
console.log(result2);
// true

13. Convert Array to an Object

To convert an array to a custom object, use reduce method.

// A function which maps a key to a value.
const arr1 = [1, 2, 3];
const result1 = arr1.reduce((acc, cur, index) => {
  acc[`attr${index}`] = cur;
  return acc;
}, {});
console.log(result1);
// { attr0: 1, attr1: 2, attr2: 3 }

// A function which count occurrences could look like this.
const arr2 = ["a", "b", "c", "c"];
const result2 = arr2.reduce((acc, cur) => {
  if (acc[cur]) {
    acc[cur] += 1;
  } else {
    acc[cur] = 1;
  }
  return acc;
}, {});
console.log(result2);
// { a: 1, b: 1, c: 2 })

// A function which maps elements in array to boolean values can look like this.
// I.e. convert array to object keys.
const arr3 = ["a", "b", "c"];
const truthValues = ["b", "c"];
const result3 = arr3.reduce((acc, cur) => {
  acc[cur] = truthValues.includes(cur);
  return acc;
}, {});
console.log(result3);
// { a: false, b: true, c: true })

14. Convert Array of Objects to an Object

To convert an array of objects to an object, use Object.assign method and array spread syntax.

const arr = [{ attr1: 1 }, { attr2: 2 }, { attr3: 3 }];
const result = Object.assign({}, ...arr);
console.log(result);
// { attr1: 1, attr2: 2, attr3: 3 }

15. Convert Object to an Array

To create an array from an object, use Object.keys, Object.values, or Object.entries, potentially together with a map method.

const obj = { a: 1, b: 2, c: 3 };

// Array of keys.
const result1 = Object.keys(obj);
console.log(result1);
// ["a", "b", "c"]

// Array of values.
const result2 = Object.values(obj);
console.log(result2);
// [1, 2, 3]

// Array of key-value objects.
const result3 = Object.entries(obj).map(([key, value]) => ({ key, value }));
console.log(result3);
// [{ key: "a", value: 1 }, { key: "b", value: 2 }, { key: "c", value: 3 }]

In some cases, it is useful to chain some map and filter methods to modify and filter out values.

const obj = { a: 1, b: 2, c: 3 };

// Array of squared values greater than 3.
const result1 = Object.values(obj)
  .map((value) => value * value)
  .filter((value) => value > 3);
console.log(result1);
// [4, 9]

// Array of key-value objects which has a value greater than 1.
const result2 = Object.entries(obj)
  .map(([key, value]) => ({ key, value }))
  .filter((keyValueObj) => keyValueObj.value > 1);
console.log(result2);
// [{ key: "b", value: 2 }, { key: "c", value: 3 }]

16. Combine Two Arrays

To combine two JavaScript arrays, use concat method or the spread syntax for arrays.

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

// Concat method is faster.
const combinedArray1 = arr1.concat(arr2);
console.log(combinedArray1);
// [1, 2, 3, 4, 5, 6]

// Spread syntax may be more readable.
const combinedArray2 = [...arr1, ...arr2];
console.log(combinedArray2);
// [1, 2, 3, 4, 5, 6]

Do not use the push method, that will mutate the original array.

17. Sort an Array

If you want to sort an array by value, use toStorted method.

The toStorted method is stable, meaning that it keeps the order of elements which are equal to each other intact. The method is not in-place, which usually is a good thing, since it means that it won't mutate the existing array.

// To sort strings.
let arr1 = ["b", "c", "a"];
const result1 = arr1.toSorted();
console.log(result1);
// ["a", "b", "c"]

// Note: Numbers are sorted by their toString value,
// not by their numerical value!
const arr2 = [10, 1, 5];
const result2 = arr2.toSorted();
console.log(result2);
// [1, 10, 5]

// To sort numbers, use a comparator.
const arr3 = [10, 1, 5];
const result3 = arr3.toSorted((a, b) => a - b);
console.log(result3);
// [1, 5, 10]

Do not use the sort method, that will mutate the original array since it does in-place sorting.

18. Sort an Array of Objects

To sort an array by value, use toStorted method with a comparator. A comparator is a function which determines which of two values that should be sorted first.

The toStorted method is stable, meaning that it keeps the order of elements which are equal to each other intact. The method is not in-place, which usually is a good thing, since it means that it won't mutate the existing array.

const arr = [{ num: 3 }, { num: 1 }, { num: 2 }];

// ObjA will be sorted before objB if comparator returns a positive value.
const byNumberAttribute = (objA, objB) => objA.num - objB.num;
const result1 = arr.toSorted(byNumberAttribute);
console.log(result1);
// [{ num: 1 }, { num: 2 }, { num: 3 }]

// More generic comparator.
const byAttribute = (attr) => (objA, objB) => objA[attr] - objB[attr];
const result2 = arr.toSorted(byAttribute("num"));
console.log(result2);
// [{ num: 1 }, { num: 2 }, { num: 3 }]

// Note. The comparator function must return an integer value.
// If you need to sort other data types, return 1, 0 or -1.
const arr3 = [{ letter: "c" }, { letter: "a" }, { letter: "b" }];
const alphabetically = (objA, objB) => {
  if (objA.letter < objB.letter) {
    return -1;
  }

  if (objA.letter > objB.letter) {
    return 1;
  }

  // objA === objB
  return 0;
};
const result3 = arr3.toSorted(alphabetically);
console.log(result3);
// [{ letter: 'a' }, { letter: 'b' }, { letter: 'c' }]

Do not use the sort method, that will mutate the original array.

19. Reverse an Array

To reverse all values in an array, use toReversed method.

const arr = [1, 2, 3];
const result = arr.toReversed(2);
console.log(result);
// [3, 2, 1]

20. Remove Duplicates From an Array

To remove duplicated elements in an array, use filter method or a set.

const arr = [1, 2, 3, 2, 1];

// Using filter method.
const result1 = arr.filter((item, index) => arr.indexOf(item) === index);
console.log(result1);
// [1, 2, 3]

// Using a set.
const result2 = [...new Set(arr)];
console.log(result2);
// [1, 2, 3]

Subscribe to my articles

...



๐Ÿ“Œ The 20 Most Common Use Cases for JavaScript Arrays


๐Ÿ“ˆ 60.09 Punkte

๐Ÿ“Œ Docker Use Cases: 15 Most Common Ways to Use Docker


๐Ÿ“ˆ 39.07 Punkte

๐Ÿ“Œ JavaScript Arrays & HashMaps: Mastering the Most Asked LeetCode Problems in Coding Interviews


๐Ÿ“ˆ 33.2 Punkte

๐Ÿ“Œ Max length of common interval whose Bitwise OR, AND are equal in both Arrays


๐Ÿ“ˆ 27.88 Punkte

๐Ÿ“Œ What is Data-as-a-Service (DaaS)? Understanding the benefits, and common use cases


๐Ÿ“ˆ 26.89 Punkte

๐Ÿ“Œ Django Model Fields โ€“ Common Use Cases and How They Work


๐Ÿ“ˆ 26.89 Punkte

๐Ÿ“Œ Demo: Creating arrays [30 of 51] | Beginner's Series to JavaScript


๐Ÿ“ˆ 25.83 Punkte

๐Ÿ“Œ How to Split an Array Into a Group of Arrays in JavaScript


๐Ÿ“ˆ 25.83 Punkte

๐Ÿ“Œ JavaScript Arrays โ€“ JS Array Funktionen erklรคrt (Cheatsheet)


๐Ÿ“ˆ 25.83 Punkte

๐Ÿ“Œ How to Merge Arrays in JavaScript โ€“ Array Concatenation in JS


๐Ÿ“ˆ 25.83 Punkte

๐Ÿ“Œ Map an Array of Arrays โ€“ JavaScript


๐Ÿ“ˆ 25.83 Punkte

๐Ÿ“Œ All You Need To Know About Arrays In JavaScript (1)


๐Ÿ“ˆ 25.83 Punkte

๐Ÿ“Œ 6 Ways to loop over arrays in Javascript


๐Ÿ“ˆ 25.83 Punkte

๐Ÿ“Œ JavaScript 2D Array โ€“ Two Dimensional Arrays in JS


๐Ÿ“ˆ 25.83 Punkte

๐Ÿ“Œ How to Filter an Array in JavaScript โ€“ JS Filtering for Arrays and Objects


๐Ÿ“ˆ 25.83 Punkte

๐Ÿ“Œ JavaScript Basics โ€“ How to Work with Strings, Arrays, and Objects in JS


๐Ÿ“ˆ 25.83 Punkte

๐Ÿ“Œ Adventures with JavaScript Arrays: Random Numbers Array


๐Ÿ“ˆ 25.83 Punkte

๐Ÿ“Œ Flattening Arrays with flat() and flatMap() in JavaScript


๐Ÿ“ˆ 25.83 Punkte

๐Ÿ“Œ How to traverse 2D arrays in JavaScript?


๐Ÿ“ˆ 25.83 Punkte

๐Ÿ“Œ Adventures with JavaScript Arrays: Sorting an Array of Numbers


๐Ÿ“ˆ 25.83 Punkte

๐Ÿ“Œ JavaScript Arrays Simplified


๐Ÿ“ˆ 25.83 Punkte

๐Ÿ“Œ ๐Ÿ”„ Looping Through JavaScript Arrays with Different Approaches ๐Ÿ”„


๐Ÿ“ˆ 25.83 Punkte

๐Ÿ“Œ How to Loop Through Arrays in JavaScript


๐Ÿ“ˆ 25.83 Punkte

๐Ÿ“Œ ECMAScript 2023 Spec for JavaScript Includes New Methods for Arrays


๐Ÿ“ˆ 25.83 Punkte

๐Ÿ“Œ The World of Sparse Arrays in JavaScript


๐Ÿ“ˆ 25.83 Punkte

๐Ÿ“Œ Navigating Arrays in JavaScript with is.array and is.not_array: Your Companion in List Adventures


๐Ÿ“ˆ 25.83 Punkte

๐Ÿ“Œ Dominando Arrays en JavaScript: Guรญa Completa


๐Ÿ“ˆ 25.83 Punkte

๐Ÿ“Œ Collect.js Tutorial โ€“ How to Work with JavaScript Arrays and Objects


๐Ÿ“ˆ 25.83 Punkte

๐Ÿ“Œ Arrays vs Objetos en JavaScript: Cuรกndo y Por Quรฉ Utilizarlos


๐Ÿ“ˆ 25.83 Punkte

๐Ÿ“Œ Dominando las Estructuras de Datos en JavaScript: Arrays, Objects, Sets y Maps


๐Ÿ“ˆ 25.83 Punkte

๐Ÿ“Œ Desestruturaรงรฃo de Arrays em JavaScript


๐Ÿ“ˆ 25.83 Punkte

๐Ÿ“Œ Minimum length of X[] after removing at most K sub-arrays


๐Ÿ“ˆ 25.39 Punkte

๐Ÿ“Œ Understanding the most common JavaScript vulnerabilities


๐Ÿ“ˆ 25.05 Punkte

๐Ÿ“Œ 13 Most Common JavaScript String Methods You Should Know About


๐Ÿ“ˆ 25.05 Punkte











matomo