Open In App

JavaScript Helper Methods

Last Updated : 14 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

An array in JavaScript is usually considered a “list-objects”. In simple words, we can say an array is an object that contains some values. But an array is a special object in JavaScript. An array can store heterogeneous data structures. It can store data values of any type like objects and array.

Example: In this example, a Javascript array is created and its values are printed in the console using the console.log() function.

Javascript




<script>
    const arr = [
      1,                        // Number type
      "Praveen kumar",          // String type
      {                         // Object type
    firstname: "Christopher",
    lastname: 'Nolan'
      },
      [9.1, 9.2, 8.7, 5]        // Array type
    ];
      
    console.log( arr );
</script>


In JavaScript, an array is an object. If an array is an object then why we don’t use an object in place of an array”. After a lot of research, we found that we can use an object in place of an array. But it comes with some caveats.

Example: In this example, both Javascript arrays and objects have been created.

Javascript




<script type="text/javascript" charset="utf-8">
        const obj = {
            "0": "Zeroth element",
            "1": "First element",
            "2": "Second element",
            "3": "Third element",
        };
        const arr = [
            "Zeroth element",
            "First element", "Second element",
            "Third element",]
        console.log(obj)
        console.log(arr);
</script>


In the above program, both an object and an array store data in exactly the same way. But there is some difference.

Output:

{0: 'Zeroth element', 1: 'First element', 2: 'Second element', 3: 'Third element'}
0
:"Zeroth element"
1:"First element"
2:"Second element"
3:"Third element"
[[Prototype]]:Object

['Zeroth element', 'First element', 'Second element', 'Third element']

0
:"Zeroth element"
1:"First element"
2:"Second element"
3:"Third element"
[[Prototype]]:Array(0)

The first one is an array that contains a property named length. It tells us the number of elements in an array. This is not the only difference. The main difference comes out when you open the __proto__ property of both an array and an object. An array comes with some great helper methods which we are going to discuss in this article. Let’s discuss some important methods.

JavaScript every() Method: This method is used to check if all elements of an array pass the test that is implemented by the passed higher-order function. What the compiler does under the hood is, iterates over the employees array and check for all employee, if he is a developer or not. As in this case, it should return false.

Input: 

 predicate function

Output:

Boolean value

Example: In this example, we will see the use of the Javascript every() method.

Javascript




<script>
    const employees = [
      { name: "Sam",      age: 25, role: "Developer" },
      { name: "John",     age: 32, role: "Manager"   },
      { name: "Ronaldo",  age: 29, role: "Architect" },
      { name: "Perker",   age: 25, role: "Developer" },
      { name: "Sophia",   age: 38, role: "Director"  },
      { name: "kristine", age: 21, role: "Developer" },
    ];
      
    function isDeveloper(employee) {
      return employee.role === "Developer";
    }
    console.log(employees.every(isDeveloper));
</script>


Output:

false

JavaScript fill() Method  : This method fills the array with a static value. It overrides all array values starting from the first element(0th index) and up to the last element(array.length-1 index).

Input:

value 

Output:

Modified array

Example: In this example, we will see the use of the Javascript fill() method.

Javascript




<script>
    const employees = [
    { name: "Sam",      age: 25, role: "Developer" },
    { name: "John",     age: 32, role: "Manager"   },
    { name: "Ronaldo",  age: 29, role: "Architect" },
    { name: "Perker",   age: 25, role: "Developer" },
    { name: "Sophia",   age: 38, role: "Director"  },
    { name: "kristine", age: 21, role: "Developer" },
    ];
          
    const newEmployees = employees.fill(
    { name: "Sam", age: 25, role: "Developer" });
    console.log(employees);
      
    console.log(newEmployees === employees);    // true
</script>


Output:

[
 { name: 'Sam', age: 25, role: 'Developer' },
 { name: 'Sam', age: 25, role: 'Developer' },
 { name: 'Sam', age: 25, role: 'Developer' },
 { name: 'Sam', age: 25, role: 'Developer' },
 { name: 'Sam', age: 25, role: 'Developer' },
 { name: 'Sam', age: 25, role: 'Developer' }
]

true

JavaScript filter() Method: This method filters the array that passes the test with the function passed to it. It returns a new array.

Input:

Predicate function

Output:

New Array with filtered elements

Example: In this example, we will see the use of the Javascript filter() method.

Javascript




<script>
    const employees = [
        { name: "Sam",      age: 25, role: "Developer" },
        { name: "John",     age: 32, role: "Manager"   },
        { name: "Ronaldo",  age: 29, role: "Architect" },
        { name: "Perker",   age: 25, role: "Developer" },
        { name: "Sophia",   age: 38, role: "Director"  },
        { name: "kristine", age: 21, role: "Developer" },
    ];
              
    function filterDevEmp(employee) {
      return employee.role === "Developer";
    }
    const filteredDevEmployees = employees.filter(filterDevEmp);
    console.log(filteredDevEmployees);
</script>


Output:

[
 { name: 'Sam', age: 25, role: 'Developer' },
 { name: 'Perker', age: 25, role: 'Developer' },
 { name: 'kristine', age: 21, role: 'Developer' }
]

JavaScript find() Method: This method returns the first element that passes the test with the provided function.

Input:

Predicate function 

Output:

Element that passes the test else undefined

Example: In this example, we will see the use of the Javascript find() method.

Javascript




<script>
    const employees = [
        { name: "Sam",      age: 25, role: "Developer" },
        { name: "John",     age: 32, role: "Manager"   },
        { name: "Ronaldo",  age: 29, role: "Architect" },
        { name: "Perker",   age: 25, role: "Developer" },
        { name: "Sophia",   age: 38, role: "Director"  },
        { name: "kristine", age: 21, role: "Developer" },
    ];
      
    function searchFirstDevEmployee(employee) {
      return employee.role === "Developer";
    }
      
    const firstEmployeeDeveloper = 
        employees.find(searchFirstDevEmployee);
      
    console.log(firstEmployeeDeveloper);  
</script>


Output:

 { name: 'Sam', age: 25, role: 'Developer' }

JavaScript findIndex() Method: This method returns the first element index that passes the test with the provided function. It can be used in the case of primitive and in the case of objects.

Input: 

Predicate function

Output: 

element index that passes the test else -1

Example: In this example, we will see the use of the Javascript findIndex() method.

Javascript




<script>
    const employees = [
        { name: "Sam",      age: 25, role: "Developer" },
        { name: "John",     age: 32, role: "Manager"   },
        { name: "Ronaldo",  age: 29, role: "Architect" },
        { name: "Perker",   age: 25, role: "Developer" },
        { name: "Sophia",   age: 38, role: "Director"  },
        { name: "kristine", age: 21, role: "Developer" },
    ];
      
    function searchFirstArchitectEmployeeIndex(employee) {
      return employee.role === "Architect";
    }
      
    const firstEmpArchitectIndex = 
      employees.findIndex(searchFirstArchitectEmployeeIndex);
      
    console.log(firstEmpArchitectIndex);  
</script>


Output:

2

JavaScript flat() Method: This method is used to flatten the array or concatenate the array with the sub-array elements recursively.

Input: 

 depth(default value is 1)

Output:

New array

Example: In this example, we will see the use of the Javascript flat() method.

Javascript




<script>
    const arr1 = [1, [2, 3, 4], 5];
    const flattened1 = arr1.flat();
    console.log(flattened1); // [ 1, 2, 3, 4, 5 ]
      
    const arr2 = [1, 2, [3, 4, [5, 6]]];
      
    const flattened2 = arr2.flat();
    console.log(flattened2); // [1, 2, 3, 4, [5, 6]] 
</script>


Output: 

[1, 2, 3, 4, 5]
[1, 2, 3, 4, [5, 6]]

JavaScript forEach() Method: This is one of the most used methods. It is used to call or execute the provided/passed function once for each element in an array. It modifies the original array.

Input: 

function

Output:

undefined

Example: In this example, we will see the use of Javascript forEach() method.

Javascript




<script>
    const employees = [
        { name: "Sam",      age: 25, role: "Developer" },
        { name: "John",     age: 32, role: "Manager"   },
        { name: "Ronaldo",  age: 29, role: "Architect" },
        { name: "Perker",   age: 25, role: "Developer" },
        { name: "Sophia",   age: 38, role: "Director"  },
        { name: "kristine", age: 21, role: "Developer" },
    ];
              
    function increaseAgeByOne(employee) {
      employee.age += 1;
    }
    employees.forEach(increaseAgeByOne);
    console.log(employees);
</script>


Output:

[
 { name: 'Sam', age: 26, role: 'Developer' },
 { name: 'John', age: 33, role: 'Manager' },
 { name: 'Ronaldo', age: 30, role: 'Architect' },
 { name: 'Perker', age: 26, role: 'Developer' },
 { name: 'Sophia', age: 39, role: 'Director' },
 { name: 'kristine', age: 22, role: 'Developer' }
]

JavaScript includes() Method: This method is used to test whether an element is present in an array or not. It checks for a value in primitive and reference in the case of an object.

Input:  

value

Output:

Boolean value weather array includes value or not

Example: In this example, we will see the use of the Javascript includes() method in an array.

Javascript




<script>
    const numbers = [1, 6, 8, 11, 5, 9, 4];
    console.log( numbers.includes(6) );  
    console.log( numbers.includes(3) );  
</script>


Output:

true
false

Example: In this example, we will see the use of Javascript includes() method in objects.

Javascript




<script>
    const arch = { name: "Ronaldo", age: 29, role: "Architect" };
      
    const employees = [
      { name: "Sam", age: 25, role: "Developer" },
      { name: "John", age: 32, role: "Manager" },
      arch,
      { name: "Perker", age: 25, role: "Developer" },
      { name: "Sophia", age: 38, role: "Director" },
      { name: "kristine", age: 21, role: "Developer" },
    ];
      
    console.log(employees.includes(arch)); 
</script>


Output:

true

JavaScript indexOf() Method: This method returns the first element index that passes the test with the provided function. It takes a value as input. It should be used in the case of primitive. As in the case of objects, it will check their reference. The check is case-sensitive.

Input: 

value

Output:

element index that passes the test else -1

Example: In this example, we will see the use of the Javascript indexOf() method.

Javascript




<script>
    const names = ["Sam", "John", "Ronaldo"
        "Perker", "Sophia", "kristine"];
    console.log(names.indexOf("John"));    
    console.log(names.indexOf("john"));
</script>


Output:

1
-1

JavaScript join() Method: This method concatenates the array values into a string separated by a comma(if no separator is provided) or with a separator provided.

Input: 

separator

Output:

New string

Example: In this example, we will see the use of the Javascript join() method.

Javascript




<script>
    const names = ["Sam", "John", "Ronaldo"
    "Perker", "Sophia", "kristine"];
    console.log( names.join() );
    console.log( names.join(" -> ") );
</script>


Output:

'Sam, John, Ronaldo, Perker, Sophia, kristine'
 'Sam -> John -> Ronaldo -> Perker -> Sophia -> kristine'

JavaScript lastIndexOf() Method: It searches for an element in an array and returns the last index of the elements provided in an array. It takes a value as input. It should be used in the case of primitive. As in the case of objects, it will check their reference.

Input: 

value

Output:

last element index that is equal(test using ===) 
to value provided else -1

Example: In this example, we will see the use of the Javascript lastIndexOf() method.

Javascript




<script>
    const roles = [ "Developer", "Manager", "Architect",
     "Developer", "Director", "Developer"];
      
    console.log(roles.lastIndexOf("Developer"));
</script>


Output:

5

JavaScript map() Method: This method call the provided function and execute this function for each element. It returns a new array.

Input:

function

Output:

new array

Example: In this example, we will see the use of the Javascript map() method.

Javascript




<script>
    const employees = [
    { name: "Sam",      age: 25, role: "Developer" },
    { name: "John",     age: 32, role: "Manager"   },
    { name: "Ronaldo",  age: 29, role: "Architect" },
    { name: "Perker",   age: 25, role: "Developer" },
    { name: "Sophia",   age: 38, role: "Director"  },
    { name: "kristine", age: 21, role: "Developer" },
    ];
      
    function getName(employee) {
      return employee.name;
    }
      
    const names = employees.map(getName);
    console.log(names);    
      
    function concetenateNameWithAge(employee) {
      return employee.name + " " + employee.age;
    }
    const nameWithAge = employees.map(concetenateNameWithAge);
    console.log(nameWithAge);
</script>


Output:

 [ 'Sam', 'John', 'Ronaldo', 'Perker', 'Sophia', 'kristine' ]
[
 'Sam 25',
 'John 32',
 'Ronaldo 29',
 'Perker 25',
 'Sophia 38',
 'kristine 21'
]

JavaScript pop() Method: It removes the last element from an array and returns the removed element.

Output: 

Removed element

Example: In this example, we will see the use of the Javascript pop() method.

Javascript




<script>
    const employees = [
    { name: "Sam",      age: 25, role: "Developer" },
    { name: "John",     age: 32, role: "Manager"   },
    { name: "Ronaldo",  age: 29, role: "Architect" },
    { name: "Perker",   age: 25, role: "Developer" },
    { name: "Sophia",   age: 38, role: "Director"  },
    { name: "kristine", age: 21, role: "Developer" },
    ];
      
    const removedEmployee = employees.pop();
    console.log(removedEmployee);    
    console.log(employees.length); 
</script>


Output:

{ name: 'kristine', age: 21, role: 'Developer' }
 5

JavaScript push() Method: It adds or pushes an element as the last element in an array.

Input:

Array element

Output: 

new length of an array

Example: In this example, we will see the use of the Javascript push() method.

Javascript




<script>
    const employees = [
    { name: "Sam",      age: 25, role: "Developer" },
    { name: "John",     age: 32, role: "Manager"   },
    { name: "Ronaldo",  age: 29, role: "Architect" },
    { name: "Perker",   age: 25, role: "Developer" },
    { name: "Sophia",   age: 38, role: "Director"  },
    { name: "kristine", age: 21, role: "Developer" },
    ];
      
    const totalEmployees = employees.push({ 
    name: "Donald", age: 21, role: "Manager" });
    console.log(employees);
    console.log( totalEmployees );
</script>


Output:

[
 { name: 'Sam', age: 25, role: 'Developer' },
 { name: 'John', age: 32, role: 'Manager' },
 { name: 'Ronaldo', age: 29, role: 'Architect' },
 { name: 'Perker', age: 25, role: 'Developer' },
 { name: 'Sophia', age: 38, role: 'Director' },
 { name: 'kristine', age: 21, role: 'Developer' },
 { name: 'Donald', age: 21, role: 'Manager' }
]
7

JavaScript reduce() Method: The array reduce() method executes the reducer function that you pass on each element and it always returns a single value. The reducer function takes 4 parameters

  • Accumulator
  • Current value
  • Array current index
  • Source Array

Note: The reducer function always returns a value and the value gets assigned to the accumulator in the next iteration.

Input: 

First argument is reducer function that takes minimum 
2 value i.e. accumulator and current value. Second 
argument is initial value of accumulator.

Output: 

A single value.

If the accumulator value is not provided then the source array’s first value or initial value is taken as the second argument of the reduce method and iteration starts from next to the initial value of the source array. 

Example: In this example, we will see the use of the Javascript reduce() method.

Javascript




<script>
    const employees = [
    { name: "Sam",      age: 25, role: "Developer" },
    { name: "John",     age: 32, role: "Manager"   },
    { name: "Ronaldo",  age: 29, role: "Architect" },
    { name: "Perker",   age: 25, role: "Developer" },
    { name: "Sophia",   age: 38, role: "Director"  },
    { name: "kristine", age: 21, role: "Developer" },
    ];
      
    function getRoleReducer(acc, currentValue) {
      acc.push(currentValue.role);
      return acc;
    }
    const roles = employees.reduce(getRoleReducer, []);
    console.log(roles);
</script>


Output:

[
 'Developer',
 'Manager',
 'Architect',
 'Developer',
 'Director',
 'Developer'
]

JavaScript reduceRight() Method: It is exactly the same as the Array reduce method but the iteration starts from right to left.

Example: In this example, we will see the use of the Javascript reduceRight() method.

Javascript




<script>
    const employees = [
     { name: "Sam",      age: 25, role: "Developer" },
     { name: "John",     age: 32, role: "Manager"   },
     { name: "Ronaldo",  age: 29, role: "Architect" },
     { name: "Perker",   age: 25, role: "Developer" },
     { name: "Sophia",   age: 38, role: "Director"  },
     { name: "kristine", age: 21, role: "Developer" },
    ];
      
    function getRoleReducer(acc, currentValue) {
      acc.push(currentValue.role);
      return acc;
    }
    const roles = employees.reduceRight(getRoleReducer, []);
    console.log(roles);
</script>


Output:

[
 'Developer',
 'Director',
 'Developer',
 'Architect',
 'Manager',
 'Developer'
]

JavaScript reverse() Method: This method reverses the array elements.

Output: 

Same array but with reversed elements

Example: In this example, we will see the use of the Javascript reverse() method.

Javascript




<script>
    const employees = [
    { name: "Sam",      age: 25, role: "Developer" },
    { name: "John",     age: 32, role: "Manager"   },
    { name: "Ronaldo",  age: 29, role: "Architect" },
    { name: "Perker",   age: 25, role: "Developer" },
    { name: "Sophia",   age: 38, role: "Director"  },
    { name: "kristine", age: 21, role: "Developer" },
    ];
      
    const reversedEmployees = employees.reverse();
    console.log(reversedEmployees);
    console.log(employees === reversedEmployees);
</script>


Output:

[
 { name: 'kristine', age: 21, role: 'Developer' },
 { name: 'Sophia', age: 38, role: 'Director' },
 { name: 'Perker', age: 25, role: 'Developer' },
 { name: 'Ronaldo', age: 29, role: 'Architect' },
 { name: 'John', age: 32, role: 'Manager' },
 { name: 'Sam', age: 25, role: 'Developer' }
]
true

JavaScript shift() Method: It removes the first element from an array and returns the removed element.

Output: 

removed element or if an array is empty returns undefined

Example: In this example, we will see the use of the Javascript shift() method.

Javascript




<script>
    const employees = [
        { name: "Sam",      age: 25, role: "Developer" },
        { name: "John",     age: 32, role: "Manager"   },
        { name: "Ronaldo",  age: 29, role: "Architect" },
        { name: "Perker",   age: 25, role: "Developer" },
        { name: "Sophia",   age: 38, role: "Director"  },
        { name: "kristine", age: 21, role: "Developer" },
    ];
      
    const removedEmployee = employees.shift();
    console.log(removedEmployee);
    console.log(employees);
</script>


Output:

{ name: 'Sam', age: 25, role: 'Developer' }
[
 { name: 'John', age: 32, role: 'Manager' },
 { name: 'Ronaldo', age: 29, role: 'Architect' },
 { name: 'Perker', age: 25, role: 'Developer' },
 { name: 'Sophia', age: 38, role: 'Director' },
 { name: 'kristine', age: 21, role: 'Developer' }
]

JavaScript slice() Method: The slice() method returns the new array with the elements specified within the starting and ending index. The new array contains the element at the starting index but does not include the element at the end index. If the end index is not provided then it is considered as an array.length-1. The slice method doesn’t change the original array.

Input:  

Start index and end index

Output: 

 New array

Example: In this example, we will see the use of the Javascript slice() method.

Javascript




<script>
    const employees = [
        { name: "Sam",      age: 25, role: "Developer" },
        { name: "John",     age: 32, role: "Manager"   },
        { name: "Ronaldo",  age: 29, role: "Architect" },
        { name: "Perker",   age: 25, role: "Developer" },
        { name: "Sophia",   age: 38, role: "Director"  },
        { name: "kristine", age: 21, role: "Developer" },
    ];
      
    const someEmployees = employees.slice(1, 3);
    console.log(someEmployees);
    console.log(employees);
</script>


Output:

[
 { name: 'John', age: 32, role: 'Manager' },
 { name: 'Ronaldo', age: 29, role: 'Architect' }
]
[
 { name: 'Sam', age: 25, role: 'Developer' },
 { name: 'John', age: 32, role: 'Manager' },
 { name: 'Ronaldo', age: 29, role: 'Architect' },
 { name: 'Perker', age: 25, role: 'Developer' },
 { name: 'Sophia', age: 38, role: 'Director' },
 { name: 'kristine', age: 21, role: 'Developer' }
]

JavaScript some() Method: This method checks if any one of the elements in the array passes the test provided by the predicate function. If in any array index the test pass some method returns true else false. It just checks the element exists in an array. It returns as soon as the predicate function returns true.

Input: 

predicate function

Output: 

Boolean

Example: In this example, we will see the use of the Javascript some() method.

Javascript




<script>
    const ages = [3, 10, 18, 20];
    let someMethod = ages.some(checkAdult);
      
    function checkAdult(age) {
      return age > 18;
    }
    console.log(someMethod)
</script>


Output:

true

JavaScript sort() Method: This method sorts the array in ascending order(default behavior if compare function is not specified). This method mutates the original array.
Input:

optional comparer function

Output:

sorted array

Example: In this example, we will see the use of the Javascript sort() method.

Javascript




<script>
    const names = ["Sam", "John", "Ronaldo", "Perker", "Sophia", "kristine"];
    names.sort();
    console.log(names);
</script>


Output:

 [ 'John', 'Perker', 'Ronaldo', 'Sam', 'Sophia', 'kristine' ]

JavaScript splice() Method: The splice() method in an array is used to add, remove, or replace elements in an array. It mutates the original array.

Input:

Starting index from where changes will takes place.
(optional) No of element to delete or remove from the start index.
(optional) The elements to add at starting index.    

Output: 

array with removed elements.

Example: In this example, we will see the use of the Javascript splice() method.

Javascript




<script>
    const employees = [
    { name: "Sam",      age: 25, role: "Developer" },
    { name: "John",     age: 32, role: "Manager"   },
    { name: "Ronaldo",  age: 29, role: "Architect" },
    { name: "Perker",   age: 25, role: "Developer" },
    { name: "Sophia",   age: 38, role: "Director"  },
    { name: "kristine", age: 21, role: "Developer" },
    ];
          
    const removedElements = employees.splice(3, 1, {
    name: "kristine",
    age: 21,
    role: "Developer",
    });
      
    console.log(removedElements);
    console.log(employees);
</script>


Output:

[ { name: 'Perker', age: 25, role: 'Developer' } ]
[
 { name: 'Sam', age: 25, role: 'Developer' },
 { name: 'John', age: 32, role: 'Manager' },
 { name: 'Ronaldo', age: 29, role: 'Architect' },
 { name: 'kristine', age: 21, role: 'Developer' },
 { name: 'Sophia', age: 38, role: 'Director' },
 { name: 'kristine', age: 21, role: 'Developer' }
]

uJavaScript nshift() Method: It adds or inserts an element at the starting position of an array.

Input: 

Element to insert

Output:  

Array length after element insertion

Example: In this example, we will see the use of the Javascript unshift() method.

Javascript




<script>
    const employees = [
        { name: "Sam",      age: 25, role: "Developer" },
        { name: "John",     age: 32, role: "Manager"   },
        { name: "Ronaldo",  age: 29, role: "Architect" },
        { name: "Perker",   age: 25, role: "Developer" },
        { name: "Sophia",   age: 38, role: "Director"  },
        { name: "kristine", age: 21, role: "Developer" },
    ];
              
    const totalNoOfemployees = employees.unshift({
        name: "kristine",
        age: 21,
        role: "Developer",
    });
      
    console.log(totalNoOfemployees);
    console.log(employees);
</script>


Output:

7
[
 { name: 'kristine', age: 21, role: 'Developer' },
 { name: 'Sam', age: 25, role: 'Developer' },
 { name: 'John', age: 32, role: 'Manager' },
 { name: 'Ronaldo', age: 29, role: 'Architect' },
 { name: 'Perker', age: 25, role: 'Developer' },
 { name: 'Sophia', age: 38, role: 'Director' },
 { name: 'kristine', age: 21, role: 'Developer' }
]


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads