Самые полезные функции для работы с массивами JavaScript - Часть 1

Опубликовано: 22 Марта, 2022

В этой статье мы собираемся обсудить следующие две функции массива JavaScript. Обе эти функции широко используются в промышленности и делают код JavaScript чистым, модульным и легким для понимания.

  1. Array.prototype.every ()
  2. Array.prototype.some ()

Array.prototype.every (): эта функция используется, когда вам нужно проверить каждый элемент данного массива. Он принимает функцию обратного вызова в качестве аргумента, который вызывается для каждого элемента массива. Функция обратного вызова должна возвращать либо истину, либо ложь. Если все элементы массива удовлетворяют функции проверки и, таким образом, функция обратного вызова возвращает истину для всех элементов массива, тогда она возвращает истину. В противном случае он возвращает false, как только встречает первый элемент, который не удовлетворяет функции валидатора.

Синтаксис:

 arr.every (обратный вызов (элемент [, индекс [, массив]]) [, thisArg])

Параметры: эта функция принимает пять параметров, как указано выше и описано ниже:

  • обратный вызов: этот параметр содержит функцию, вызываемую для каждого элемента массива.
  • currentValue: параметр содержит значение элементов, обрабатываемых в данный момент.
  • index: этот параметр является необязательным, он содержит индекс элемента currentValue в массиве, начиная с 0.
  • array: этот параметр является необязательным, он содержит полный массив, для которого вызывается Array.every.
  • thisArg: этот параметр является необязательным, он содержит контекст, который должен быть передан как this, который будет использоваться при выполнении функции обратного вызова. Если контекст передан, он будет использоваться как this для каждого вызова функции обратного вызова, в противном случае по умолчанию используется undefined.

Примеры: Учитывая массив, напишите функцию, чтобы проверить, все ли элементы этого массива меньше 100 или нет.

  • Program 1: In this code, we will check the array by using a loop function. So the naive approach is to use for a loop as shown below.

    Although the below implementation is easy to understand for any novice programmer, there are some un-necessary checks which the programmer has to take care of. For example, the short-circuiting mechanism i.e. the programmer has to explicitly make sure that as soon as the loop encounters the first element which fails the given condition, the loop should break and return false. Also until and unless the programmer dives deep into the logic of the code, he/she won’t be able to understand what this for loop is doing.

    let numbers = [30,60,190];
    let result = true;
    for (let i = 0; i < numbers.length; i++) {
        if (numbers[i] >= 100) {
            result = false;
            break;
        }
    }
    document.write(result);

    Output:

    false
  • Program 2: In this code, we will check the array by using a Array.prototype.every() function. So the naive approach is to use for a loop as shown below.

    with the use of Array.every(), the same behavior can be achieved with much clearer, intuitive and less code.

    let numbers = [30,60,90];
    let result = numbers.every(function(element){
       return(element < 100);
     });
       
    document.write(result);

    Output:

    true

Examples: Given an array, write a function to check if all elements of that array are of a specified data type.

  • Program 1: Again naive approach would be to iterate over the array using for loop. This code snippet has the same loopholes as the previous example.
     
    function fnCheckDatatype_Every(arr, sDatatype){
        for(var i = 0 ; i < arr.length; i ++)
        {
          if(typeof(arr[i]) !== sDatatype)
          {
              return false;
          }
        }
    }
      
    fnCheckDatatype_Every(["Geeks",4,"Geeks"],"string");
    fnCheckDatatype_Every(["Geeks","for","Geeks"],"string");
    true
    false
    
  • Program 2: Using arr.Every() those loopholes are taken care of again in the code snippet below. Another point to note in the code snippet below is that we are passing two arguments to the array.every() function. The first one is the callback function (anonymous function in our case) and the second one is sDatatype. Because we need an external variable in each call of a callback function, we pass it as a second argument as ‘this’ variable.
    function fnCheckDatatype_Every(arr, sDatatype){
    return arr.every(function(element){
                return typeof(element) === sDatatype;
            },sDatatype);
    }
      
    fnCheckDatatype_Every(["Geeks","for","Geeks"],"string");
    fnCheckDatatype_Every(["Geeks",4,"Geeks"],"string");

    Output:

    true
    false
    

Array.prototype.some(): This is in a way opposite to Array.every(). This function is used when you need to check if at least one element of a given array passes the test implemented by the callback function. Array.some() accepts a callback function as argument which has to return either a true or false. The callback function is called for each element of the array until it returns true for at least one element of the array. If neither of the elements in the array pass the test of callback function, it returns false.



Syntax:

arr.some(callback(element[, index[, array]])[, thisArg])

Parameters: This function accepts four parameter as mentioned above and described below:

  • callback: This parameter holds the function to be called for each element of the array.
  • currentValue: The parameter holds the value of the elements being processed currently.
  • index: This parameter is optional, it holds the index of the currentValue element in the array starting from 0.
  • array: This parameter is optional, it holds the complete array on which Array.every is called.
  • thisArg This parameter is optional, it holds the context to be passed as this to be used while executing the callback function. If the context is passed, it will be used as this for each invocation of the callback function, otherwise undefined is used as default.

Examples: Given an array, write a function to check if an array contains any number greater than 100.

  • Program 1: Naive Approach
    function fnIsGreaterThan100_loop(arr){
        for(var i = 0 ; i < arr.length; i ++){
          if(arr[i] > 100){
              return true;
          }
       }
       return false;
    }
      
    fnIsGreaterThan100_loop([30,60,90,120]);
    fnIsGreaterThan100_loop([30,60,90]);

    Output:

    true
    false
    
  • Program 2:Using Array.some()
    function fnIsGreaterThan100_some(arr){
         return arr.some(function(element){
                return(element> 100);
         });
    }
      
    fnIsGreaterThan100_some([30,60,90,120]);
    fnIsGreaterThan100_some([30,60,90]);

    Output:

    true
    false
    

Examples: Given an array, write a function to check if an array contains an even number.

  • Program 1: Naive approach
    function fnIsEven_loop(arr){
        for(var i = 0 ; i < arr.length; i ++){
          if(arr[i] % 2 === 0){
              return true;
          }
        }
        return false;
    }
      
    fnIsEven_loop([1,3,5]);
    fnIsEven_loop([1,3,5,6]);

    Output:

     false
     true
    
  • Program 2: Using Array.some()
    function fnIsEven_some(arr){
           return arr.some(function(element){
                return(element %2 === 0);
           });
    }
      
    fnIsEven_some([1,3,5]);
    fnIsEven_some([1,3,5,6]);

    Output:

     false
     true
    

One of the common mistakes programmers do while using array functions like Array.every() and Array.some() is that they forget the return the value in the callback function. Mind it, if you don’t return any value from the callback function, null is returned which will be interpreted as false.

Also, it is important to know that these array functions were introduced in ECMAScript 5. So these functions are supported in IE9 or higher. If you need to use it for older browsers as well, then a library like underscore.js can come to your rescue which has an equivalent implementation of such functions.

Must use JavaScript Array Functions -Part 2

Must use JavaScript Array Functions -Part 3

Additionally, if you wish to dive deeper into the above functions, you can refer to following official links
1. http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.16
2. http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.17

About the author:

“Harshit is a technology enthusiast and has keen interest in programming. He holds a B.Tech. degree in Computer Science from JIIT, Noida and currently works as Front-end Developer at SAP. He is also a state level table tennis player. Apart from this he likes to unwind by watching movies and English sitcoms. He is based out of Delhi and you can reach out to him at https://in.linkedin.com/pub/harshit-jain/2a/129/bb5

If you also wish to showcase your blog here,please seeGBlog for guest blog writing on GeeksforGeeks.