|
| 1 | +// Create an Array |
| 2 | +let fruits = ['Apple', 'Banana'] |
| 3 | + |
| 4 | +/** |
| 5 | + * Common Operations |
| 6 | + * length |
| 7 | + * access |
| 8 | + * iterate/loop |
| 9 | + * push |
| 10 | + * pop |
| 11 | + * indexOf |
| 12 | + * shift |
| 13 | + * unshift |
| 14 | + * splice |
| 15 | + * slice |
| 16 | + */ |
| 17 | + |
| 18 | +// length |
| 19 | +console.log(fruits.length) // 2 |
| 20 | + |
| 21 | +// Access an Array item using the index position |
| 22 | +console.log(fruits[0]) // Apple |
| 23 | + |
| 24 | +// Loop over an Array |
| 25 | +fruits.forEach(function (item, index, array) { |
| 26 | + console.log(item, index) |
| 27 | +}) |
| 28 | +// Apple 0 |
| 29 | +// Banana 1 |
| 30 | + |
| 31 | +// Add an item to the end of an Array |
| 32 | +let newLength = fruits.push('Orange') |
| 33 | +// ["Apple", "Banana", "Orange"] |
| 34 | + |
| 35 | +// Remove an item from the end of an Array |
| 36 | +let last = fruits.pop() // remove Orange (from the end) |
| 37 | +// ["Apple", "Banana"] |
| 38 | + |
| 39 | +// Remove an item from the beginning of an Array (reverse of pop) |
| 40 | +let first = fruits.shift() // remove Apple from the front |
| 41 | +// ["Banana"] |
| 42 | + |
| 43 | +// Add an item to the beginning of an Array (reverse of push) |
| 44 | +fruits.unshift('Strawberry') // add to the front |
| 45 | +// ["Strawberry", "Banana"] |
| 46 | + |
| 47 | +// Find the index of an item in the Array |
| 48 | +fruits.push('Mango') |
| 49 | +// ["Strawberry", "Banana", "Mango"] |
| 50 | + |
| 51 | +let pos = fruits.indexOf('Banana') // case sensitive; returns -1 if not found |
| 52 | +// 1 |
| 53 | + |
| 54 | +// Remove an item by index position |
| 55 | +let removedItem = fruits.splice(pos, 1) // this is how to remove an item |
| 56 | +// ["Strawberry", "Mango"] |
| 57 | + |
| 58 | +// Remove items from an index position |
| 59 | +let vegetables = ['Cabbage', 'Turnip', 'Radish', 'Carrot'] |
| 60 | +console.log(vegetables) |
| 61 | +// ["Cabbage", "Turnip", "Radish", "Carrot"] |
| 62 | + |
| 63 | +let pos = 1 |
| 64 | +let n = 2 |
| 65 | + |
| 66 | +let removedItems = vegetables.splice(pos, n) |
| 67 | +// this is how to remove items, n defines the number of items to be removed, |
| 68 | +// starting at the index position specified by pos and progressing toward the end of array. |
| 69 | + |
| 70 | +console.log(vegetables) |
| 71 | +// ["Cabbage", "Carrot"] (the original array is changed) |
| 72 | + |
| 73 | +console.log(removedItems) |
| 74 | +// ["Turnip", "Radish"] |
| 75 | + |
| 76 | +// Copy an Array |
| 77 | +let shallowCopy = fruits.slice() // this is how to make a copy |
| 78 | +// ["Strawberry", "Mango"] |
| 79 | + |
| 80 | +console.log(fruits) |
| 81 | +//["Strawberry", "Mango"] (the original array remain same) |
0 commit comments