20개 이상의 유용한 JavaScript 배열 방법 치트시트

24561 단어 javascriptwebdev

목차



Arrays
  • Array.push()
  • Array.unshift()
  • Array.pop()
  • Array.shift()
  • Array.splice()
  • Array.concat()
  • Array.isArray()
  • Array.slice()
  • Array.length
  • Array.includes()
  • Array.from()
  • Array.fill()
  • Array.filter()
  • Array.find()
  • Array.forEach()
  • Array.map()
  • Array.flat()
  • Array.reverse()
  • Array.every()
  • Array.copyWithin()
  • Array.reduce()
  • Array.flatMap()
  • Array.some()
  • Array.of()
  • Array.sort()
  • Array.join()
  • Array.toLocaleString()
  • Array.keys()
  • Array.values()
  • Array.entries()

  • Conclusion

    배열

    If we talk in programming language, an array is said to be a collection of elements or items. They store data as elements and can retrieve them back whenever you need them. It is a widely used data structure in the programming languages that support it.
    In JavaScript, we can use a pair of square brackets [] to represent an array. Every single element in the array is separated by a comma(,). They can be a collection of elements of any data type, meaning that you can create an array with elements of data type String, Boolean, Number, Objects, and even other Arrays. They are used to store multiple values in a single variable.

    Syntax:

    const array_name = [itemA, itemB, itemC,.............];   
    

    Example:

    const flowers = ["lily", "rose", "tulip"];
    console.log(flowers);
    

    Output:

    lily, rose, tulip
    

    Arrays truly are a wonder in JavaScript. They have many useful built-in properties or methods that can help you resolve any task involving them. Let's discuss the most important and useful ones now.

    1. Array.push()

    This method adds elements at the end of an array.

    Example:

    // Declaring and initializing our number array
    var number_arr = [ 1, 2, 3, 4, 5];
    
    // Adding 6 to the end of the array
    number_arr.push(6);
    
    console.log(number_arr);
    

    Output:

    1, 2, 3, 4, 5, 6
    

    2. Array.unshift()

    It is the opposite of array.push(). This method adds elements to the front of the array.

    Example:

    // Declaring and initializing our number array
    var number_arr = [ 1, 2, 3, 4, 5];
    
    // Now adding 6 to the front of the array
    number_arr.unshift(6);
    
    console.log(number_arr);
    

    Output:

    6, 1, 2, 3, 4, 5, 
    

    3. Array.pop()

    This method removes elements from the end of the array.

    Example:

    // Declaring and initializing our number array
    var number_arr = [ 1, 2, 3, 4, 5];
    
    // It will remove element from end of the array
    number_arr.pop();
    
    console.log(number_arr);
    

    Output:

    1, 2, 3, 4,  
    

    4. Array.shift()

    It is the opposite of array.pop(). It removes elements from the front of the array.

    Example:

    // Declaring and initializing our number array
    var number_arr = [ 1, 2, 3, 4, 5];
    
    // Removing element from front of the array
    number_arr.shift();
    
    console.log(number_arr);
    

    Output:

    2, 3, 4, 5 
    

    5. Array.splice()

    It is a very useful method. It can remove or add elements from or in any particular location of the array.

    Example:

    // Adding elements using splice()
    const fruits = ["Banana", "Orange", "Apple", "Mango"];
    
    // At position 2, adding 2 elements
    fruits.splice(2, 0, "Lemon", "Kiwi");
    
    console.log(fruits);
    
    // Removing elements using splice()
    
    const number_arr = [ 2, 3, 4, 5, 6 ];
    
    // using splice() to delete 3 elements starting from index 1
    number_arr.splice(1, 3);
    
    console.log(number_arr);
    
    

    Output:

    Banana, Orange, Lemon, Kiwi, Apple, Mango
    2, 6
    

    6. Array.concat()

    This method is used to join two or more arrays.

    Example:

    // Declaring and initializing our arrays
    
    const fruits = ["apple", "orange"];
    const vegetables = ["potato", "capsicum", "carrot"];
    
    const all = fruits.concat(vegetables);
    
    console.log(all);
    

    Output:

    apple, orange, potato, capsicum, carrot
    

    7. Array.isArray()

    It determines whether the value passed through it is an array or not and returns the answer in booleans (true or false).

    Example:

    // Declaring and initializing our array
    
    const fruits = ["apple", "orange"];
    Array.isArray(fruits);
    
    

    Output:

    True
    

    8. Array.slice()

    This method returns selected elements from an array, as a new array.

    Example:

    // Declaring and initializing our array
    
    const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
    const citrus = fruits.slice(1, 3);
    console.log(citrus);
    
    

    Output:

    Orange, Apple
    

    9. 배열.길이

    This method returns or sets the number of elements in an array.

    Example:

    // Declaring and initializing our array
    
    const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
    
    // Checking the length of the array
    const len = fruits.length;
    
    // Printing the result
    console.log(len);
    
    

    Output:

    5
    

    10. Array.includes()

    This method checks if an array has a certain value among its elements.

    Example:

    // Initializing and declaring our array
    let fruits = ["Banana", "Apple", "Mango", "Peach", "Orange, "Grapes"];
    
    let check = fruits.includes("Apple");
    console.log(check); // true
    
    // This method is case sensitive
    
    let check1 = fruits.includes("apple");
    console.log(check1); // false
    
    // The second argument here specifies position to start searching from
    
    let check2 = fruits.includes("Apple", 2);
    console.log(check2); // false
    
    // The negative argument here starts the count from backwards
    // Searching starts from third-to-last element
    
    let check3 = fruits.includes("Apple", -3);
    console.log(check3); // false
    
    let check4 = fruits.includes("Lime");
    console.log(check4); // false
    
    

    Output:

    true
    false
    false
    false
    false
    

    11. Array.from()

    This method creates a new but shallow-copied Array instance from an array-like or iterable object.

    Example:

    console.log(Array.from('hello'));
    // output: Array ["h", "e", "l", "l", "o"]
    
    console.log(Array.from([2, 3, 4], x => x + x));
    // expected output: Array [4, 6, 8]
    
    

    12. Array.fill()

    This method changes all elements in an array to a static value, from a start index (default 0) to an end index (default array.length). It returns the modified array.

    Example:

    const arrayA = [1, 2, 3, 4];
    
    // fill with 1 from position 2 until position 4
    console.log(arrayA.fill(0, 2, 4));
    // output: [1, 2, 1, 1]
    
    // fill with 6 from position 1
    console.log(arrayA.fill(5, 1));
    // output: [1, 6, 6, 6]
    
    console.log(arrayA.fill(8));
    // output: [8, 8, 8, 8]
    

    13. Array.filter()

    This method creates a new array with all elements that pass the test implemented by the provided function.

    Example:

    const words = ['hello', 'hi', 'elite', 'amazing', 'adios', 'present'];
    
    const result = words.filter(word => word.length > 6);
    
    console.log(result);
    // output: Array ["amazing", "present"]
    

    14. Array.find()

    This method returns the value of the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.

    Example:

    const arrayA = [7, 12, 8, 140, 54];
    
    const found = arrayA.find(element => element > 10);
    
    console.log(found);
    // output: 12
    
    

    15. Array.forEach()

    This method executes a provided function once for each array element.

    Example:

    const arrayA = ['c', 'd', 'e'];
    
    arrayA.forEach(element => console.log(element));
    
    // output: "c"
    // output: "d"
    // output: "e"
    
    

    16. Array.map()

    This method creates a new array populated with the results of calling a provided function on every element in the calling array.

    Example:

    const arrayA = [3, 4, 7, 16];
    
    // pass a function to map
    const map1 = arrayA.map(x => x * 2);
    
    console.log(map1);
    // output: Array [6, 8, 14, 32]
    

    17. Array.flat()

    This method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

    Example:

    const arrA = [0, 1, 2, [5, 7]];
    
    console.log(arrA.flat());
    // output: [0, 1, 2, 5, 7]
    
    const arrB = [0, 1, 2, [[[5, 7]]]];
    
    console.log(arrB.flat(2));
    // output: [0, 1, 2, [5, 7]]
    
    

    18. Array.reverse()

    This method reverses an array in place. The first array element becomes the last, and the last array element becomes the first.

    Example:

    const arrayA = ['A', 'B', 'C'];
    console.log('arrayA:', arrayA);
    // output: "arrayA:" Array ["A", "B", "C"]
    
    const reversed = arrayA.reverse();
    console.log('reversed:', reversed);
    // output: "reversed:" Array ["C", "B", "A"]
    
    console.log('arrayA:', arrayA);
    // output: "arrayA:" Array ["C", "B", "A"]
    

    19. Array.every()

    This method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.

    Example:

    const isBelow = (currentValue) => currentValue < 50;
    
    const arrayA = [3, 0, 39, 19, 40,45];
    
    console.log(arrayA.every(isBelow));
    // output: true
    

    20. Array.copyWithin()

    This method shallow copies part of an array to another location in the same array and returns it without modifying its length.

    Example:

    const arrayA = ['A', 'B', 'C', 'D', 'E'];
    
    // copy to index 0 the element at index 3
    console.log(arrayA.copyWithin(0, 3, 4));
    // output: Array ["D", "B", "C", "D", "E"]
    
    // copy to index 1 all elements from index 3 to the end
    console.log(arrayA.copyWithin(1, 3));
    // output: Array ["D", "D", "E", "D", "E"]
    
    

    21. Array.reduce()

    The easiest-to-understand explanation for reduce() is that it returns the sum of all the elements in an array. It walks through the array element-by-element and at each step, it adds the current array value to the result from the previous step until there are no more elements to add.

    Moreover, it can also apply any callback function such as mean, median, count, etc. The sum is the simplest and easiest to understand use case!

    Example:

    const arrayA = [3, 2, 8, 4];
    const reducer = (previousValue, currentValue) => previousValue + currentValue;
    
    // 3 + 2 + 8 + 4
    console.log(arrayA.reduce(reducer));
    // output: 17
    
    // 5 + 3 + 2 + 8 + 4
    console.log(arrayA.reduce(reducer, 5));
    // output: 22
    

    22. Array.flatMap()

    This method returns a new array that is basically formed by applying a given callback function to each element of the array, and then flattening the result by one level. It is identical to a map() followed by a flat() of depth 1. But it is slightly more efficient and time-saving than calling those two methods separately.

    Example:

    let arrA = [3, 2, 9, 4];
    
    arrA.flatMap(x => [x * 2]);
    // [6, 4, 18, 8]
    
    // only one level is flattened
    arrA.flatMap(x => [[x * 2]]);
    // [[3], [4], [9], [8]]
    

    23. Array.some()

    This method checks to see if at least one of array’s item passed a certain pre-defined condition. If passed, it return "true" otherwise "false".

       const arrayA = [1, 2, 3, 4, 5, 6];
    
      // at least one element is greater than 3?
      const largeNum = arr.some(num => num > 3);
      console.log(largeNum); 
      // output: true
    
    

    24. Array.of()

    This method create array from every arguments passed into it.

      const alphabets = Array.of(a, b, c, d, e, f);
      console.log(alphabets); 
      // output: [a, b, c, d, e, f]
    

    25. Array.sort()

    This method is used to sort any array’s items either in ascending or descending order.

      const numbers = [1, 2, 3, 4, 5, 6];
      const alphabets = ['d', 'a', 'c', 't', 'z'];
    
      //sort in descending order
      descOrder = numbers.sort((a, b) => a > b ? -1 : 1);
      console.log(descOrder); 
      //output: [6, 5, 4, 3, 2, 1]
    
      //sort in ascending order
      ascOrder = alphabets.sort((a, b) => a > b ? 1 : -1);
      console.log(ascOrder); 
      //output: ['a', 'c', 'd', 't', 'z']
    
    

    26. Array.join()

    It creates and returns a new string by concatenating all of the elements in an array separated by commas or a specified separator string. But if the array consists of one item, then that item will be returned without using the separator.

    const elements = ['Hi', 'Hello', 'Bye'];
    
    console.log(elements.join());
    // output: "Hi,Hello,Bye"
    
    console.log(elements.join(''));
    // output: "HiHelloBye"
    
    console.log(elements.join('-'));
    // output: "Hi-Hello-Bye"
    

    27. Array.toLocaleString()

    This method returns a string representing the elements of the array. The elements are converted to Strings using their toLocaleString methods. Then those Strings are separated by a locale-specific String (such as a comma “,”).

    const array1 = [1, 'a', new Date('29 Dec 2002 16:12:00 UTC')];
    const localeString = array1.toLocaleString('en', { timeZone: 'UTC' });
    
    console.log(localeString);
    // output: "1,a,12/29/2002, 4:12:00 PM",
    

    28. Array.keys()

    This method returns a new Array Iterator object that contains the keys for each index in the array.

    const arrayA = ['A', 'B', 'C', 'D'];
    const iterator = arrayA.keys();
    
    for (const key of iterator) {
      console.log(key);
    }
    
    // output: 0
    // output: 1
    // output: 2
    // output: 3
    

    29. Array.values()

    This method returns a new array iterator object that contains the values for each index in the array.

    const arrayA = ['A', 'B', 'C', 'D'];
    const iterator = arrayA.keys();
    
    for (const value of iterator) {
      console.log(value);
    }
    
    // output: A
    // output: B
    // output: C
    // output: D
    

    30. Array.entries()

    This method returns a new Array Iterator object that contains the key/value pairs for each index in the array.

    const arrayA = ['A', 'B', 'C'];
    
    const iterator1 = arrayA.entries();
    
    console.log(iterator1.next().value);
    // output: Array [0, "A"]
    
    console.log(iterator1.next().value);
    // output: Array [1, "B"]
    

    결론

    JavaScript arrays have quite a lot of useful methods that can simplify our development efforts. Knowing these methods can save us time and can even boost the performance of our code. I truly hoped that today you all learned something today, whether it was new array methods or refreshing your old concepts which you can use for your next project ^_^

    Let's connect!

    Github

    좋은 웹페이지 즐겨찾기