Notes

Array.every()

Edit on GitHub

JavaScript
2 minutes

.every()

The every() method return true/false based on whether or not every element in the source array passes a certain condition or not

You’ll exit on the first failure. If the condition returns false for something, it stop processing the array there and returns.

Examples

1// EXAMPLE 1
2const items = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
3const result = items.every(x => x < 10) // check every item is <10?
4const result2 = items.every(x => x > 5) // check every item is >5?
5
6console.info('result:', result) // result: true
7console.info('result2:', result2) // result2: false

Check if an array contains only strings

1// EXAMPLE 2
2const items2 = [1, 4, 7, 'hello', 'blah']
3const strings = items2.every(x => typeof x === 'string') // check if every items is a string?
4console.info('strings:', strings) // strings: false

Check if a form submission was valid

 1// EXAMPLE 3
 2const fields = [
 3	{
 4		field: 'email',
 5		value: 'shane@email.com',
 6		errors: []
 7	},
 8	{
 9		field: 'name',
10		value: '',
11		errors: ['No name provided']
12	}
13]
14
15const isValid = fields.every(x => x.errors.length === 0 ) // check if no errors?
16console.info('isValid:', isValid) // isValid: false

Check if a user has finished watching the course

 1// EXAMPLE 4
 2const videos = [
 3	{
 4		title: 'Array methods in depth: concat',
 5		length: 310, // video length in secs
 6		viewed: 310	// amount of secs watched
 7	},
 8	{
 9		title: 'Array methods in depth: join',
10		length: 420,
11		viewed: 360
12	}
13]
14const isComplete = videos.every(x => x.viewed === x.length)
15console.info('isComplete:', isComplete) // isComplete: false

Related