|
| 1 | +## Array additions |
| 2 | + |
| 3 | +```js |
| 4 | +// ES5 |
| 5 | +console.log( |
| 6 | + [2,5,10,4,7,8,13,15].indexOf(10) //2 |
| 7 | +) |
| 8 | + |
| 9 | +console.log( |
| 10 | + [2,5,10,4,7,8,13,15].indexOf(10) > -1 // true |
| 11 | +) |
| 12 | +``` |
| 13 | + |
| 14 | +* new ES6 Array methods: |
| 15 | + |
| 16 | + * includes() |
| 17 | + * find() * when we need to use a CONDITION |
| 18 | + * findIndex() |
| 19 | + * .fill() |
| 20 | + * .keys() |
| 21 | + * .values() |
| 22 | + * .enteries() |
| 23 | + |
| 24 | +#### .includes() |
| 25 | + |
| 26 | +```js |
| 27 | +console.log( |
| 28 | + [2,5,10,4,7,8,13,15].includes(25) // false (there is no 25 in the array) |
| 29 | +) |
| 30 | +``` |
| 31 | + |
| 32 | +#### .find() |
| 33 | + |
| 34 | +```js |
| 35 | +console.log( |
| 36 | + [2,5,10,4,7,8,13,15].find(function(item){ |
| 37 | + // condition |
| 38 | + // return item === 7 // return the FIRST item that meets this condition |
| 39 | + // return item > 8 // 10 (note that although 13 is greater than 8 but .find method starts from the beginning of the array and stops when meets the criteria) |
| 40 | + return item % 2 !== 0 // 5 |
| 41 | + }) |
| 42 | +) |
| 43 | +``` |
| 44 | +* another example: the objective of this example is to find the user(s) who is admin. |
| 45 | + |
| 46 | +```js |
| 47 | +class User { |
| 48 | + constructor(name, isAdmin) { |
| 49 | + this.name = name; |
| 50 | + this.isAdmin = isAdmin; |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +let users = [ |
| 55 | + new User('Massih', false), |
| 56 | + new User('Ehsan', true), |
| 57 | + new User('Alex', false) |
| 58 | +]; |
| 59 | + |
| 60 | +// find the first user that is admin |
| 61 | +console.log( |
| 62 | + users.find(user => user.isAdmin) // {name: "Ehsan", isAdmin: true} |
| 63 | + users.find(user => user.isAdmin).name // Ehsan |
| 64 | +) |
| 65 | +``` |
| 66 | + |
| 67 | +#### .enteries() |
| 68 | + |
| 69 | +> note that when using .enteries(), the items.indexOf() won't work |
| 70 | +
|
| 71 | +```js |
| 72 | +// without .enteries() |
| 73 | +let items = ['item1', 'item2', 'item3']; |
| 74 | +for (let item of items) { |
| 75 | + console.log( |
| 76 | + `${item} with index of: ${items.indexOf(item)}` |
| 77 | + ) |
| 78 | +} |
| 79 | + |
| 80 | +// using .enteries() |
| 81 | +let items = ['item1', 'item2', 'item3'].entries(); |
| 82 | +for (let item of items) { |
| 83 | + console.log( |
| 84 | + `${item}` // returns: index,item for example (0,item1,1,item2,...) |
| 85 | + ) |
| 86 | +} |
| 87 | +``` |
0 commit comments