HomeAbout MeContact

The some() Array Methods in JavaScript and how to use it .

By Gopal Baskota
Published in JavaScript
January 03, 2021
1 min read

some method in JavaScript is used to determine whether at least one of the elements of the array satisfies the given condition or not.

Some () Method

  • Iterates through an array

  • Runs a callback on each value in the array

  • If the callback returns true for at least one single value, return true

    Otherwise, return false

  • the result of the callback will always be a Boolean.

Example :

let numbers = [2,3,5];

numbers.some(function(value, index, array){
  return value < 3;
});

// true

let numbers = [2,3,5];

numbers.some(function(value, index, array){
  return value > 10;
});

// false

How does it work ?

function some(array, callback){
  for(let i = 0; i < array.length; i++){ //Iterates through an array
    if(callback(array[i], i, array) === true){ //Runs a callback on each value in the array
      return true; //If the callback returns true for at least one single value, return true
    }
  }
  return false; //Otherwise, return false
}

How to use some() method in a function .

const hasPassed = (arr) => {
  return arr.some(function(value){
    return value.passed
  });
}

hasPassed([{name: "gopal"}, {name: "john", passed: false}]); //false

hasPassed([{name: "gopal", passed:true}, {name: "john", passed: false}]); //true

When to use some() method

  1. You need to determine if at least one value in an array exists and you have to determine this by using a callback .
  2. To see if the array contains at least one element

Next : The every() Array Methods in JavaScript and how to use it .


Tags

Javascriptsomeeveryarraymethods
Previous Article
Rendering HTML in React

Gopal Baskota

Full stack Web Developer

Topics

JavaScript
NodeJs
React Js

Related Posts

get the last element of an array in JavaScript.
May 18, 2020
1 min
© 2021, All Rights Reserved.

Quick Links

Advertise with usAbout UsContact Us

Social Media