20 Array Methods – DEV Community

/*
Under is a listing of 20 array strategies. For every technique, there is a description on the prime (stolen straight from MDN) and a number of examples.

I needed all the 20 in the identical place, and arranged a sure manner, for myself, and I figured I'll as nicely share it as a result of it may additionally be useful to others.

Please notice that a few of these strategies are extra sophisticated than others. And a few could also be easy within the examples I've included however have way more sophisticated makes use of. The perfect instance of one in every of these extra sophisticated strategies is cut back(). To learn extra about cut back() (simply to take one instance), go to https://developer.mozilla.org/en-US/docs/Internet/JavaScript/Reference/Global_Objects/Array/Scale back.

Please notice that among the 20 array strategies I've included do modify the unique array, and a few don't. For instance, push(), pop(), unshift(), and shift() do, and forEach(), filter(), map(), and cut back() don't. In most, although not all, of the MDN descriptions that I've included, it's talked about whether or not the unique array is modified or not. However one other clue is that this: Should you view my instance for the reverse() technique (simply to take one instance), you may discover that within the second line the tactic is placed on the array and that within the third line solely the array title itself (i.e., with none technique on it) is handed in to console.log(), and but a modified array is what's logged to the console.
*/


// 1. The push() technique provides a number of components to the tip of an array and returns the brand new size of the array.

const pushDemoArr = [10, 20, 30, 40, 50]
console.log(pushDemoArr.push(60)) // 6
console.log(pushDemoArr) // [10, 20, 30, 40, 50, 60]


// 2. The pop() technique removes the final aspect from an array and returns that aspect. This technique adjustments the size of the array.

const popDemoArr = [10, 20, 30, 40, 50]
console.log(popDemoArr.pop()) // 50
console.log(popDemoArr) // [10, 20, 30, 40]


// 3. The unshift() technique provides a number of components to the start of an array and returns the brand new size of the array.

const unshiftDemoArr = [10, 20, 30, 40, 50]
console.log(unshiftDemoArr.unshift(0)) // 6
console.log(unshiftDemoArr) // [0, 10, 20, 30, 40, 50]


// 4. The shift() technique removes the primary aspect from an array and returns that eliminated aspect. This technique adjustments the size of the array.

const shiftDemoArr = [10, 20, 30, 40, 50]
console.log(shiftDemoArr.shift()) // 10
console.log(shiftDemoArr) // [20, 30, 40, 50]


// 5. The forEach() technique executes a supplied operate as soon as for every array aspect.

const forEachDemoArr = [10, 20, 30, 40, 50]
forEachDemoArr.forEach(val => { console.log(val + 3) }) // 13 23 33 43 53


// 6. The filter() technique creates a brand new array with all components that move the check applied by the supplied operate.

const filterDemoArr = [10, 20, 30, 40, 50]
const newFilterDemoArr = filterDemoArr.filter(val => { return val > 25 }) // i.e., if a quantity in filterDemoArr is larger than 25, then add it to newFilterDemoArr
console.log(newFilterDemoArr) // [30, 40, 50]


// 7. The map() technique creates a brand new array populated with the outcomes of calling a supplied operate on each aspect within the calling array.

const mapDemoArr = [10, 20, 30, 40, 50]
const newMapDemoArr = mapDemoArr.map(val => { return val + 5 })
console.log(newMapDemoArr) // [15, 25, 35, 45, 55]


// 8. The cut back() technique executes a user-supplied "reducer" callback operate on every aspect of the array, so as, passing within the return worth from the calculation on the previous aspect. The ultimate results of operating the reducer throughout all components of the array is a single worth.

// Under are three examples of cut back().

// With out an initialValue, which signifies that reduceDemoArr1 is handled as it's: [10, 20, 30, 40, 50]
const reduceDemoArr1 = [10, 20, 30, 40, 50]
const sum1 = reduceDemoArr1.cut back((accumulator, currentVal) => { return accumulator + currentVal }) 
console.log(sum1) // 150

// With an initialValue of 0, which signifies that reduceDemoArr2 is handled as: [0, 10, 20, 30, 40, 50]
const reduceDemoArr2 = [10, 20, 30, 40, 50]
const sum2 = reduceDemoArr2.cut back((accumulator, currentVal) => { return accumulator + currentVal }, 0) 
console.log(sum2) // 150

// With an initialValue of 100, which signifies that reduceDemoArr3 is handled as: [100, 10, 20, 30, 40, 50]
const reduceDemoArr3 = [10, 20, 30, 40, 50]
const sum3 = reduceDemoArr3.cut back((accumulator, currentVal) => { return accumulator + currentVal }, 100) 
console.log(sum3) // 250

/* Extra notes on cut back() which may be useful:
- Though cut back() is getting used for addition within the three examples above, cut back() isn't inherently including, or multiplying, or something. Do not make the error of considering that it's, as a result of considering so could make issues very complicated with extra complicated makes use of of cut back(). cut back() returns one worth ultimately based mostly on the situations supplied.
- As is written right here https://medium.com/swlh/javascript-reduce-with-examples-570f1b51e854, the "accumulator" will also be referred to as the "previousValue", as a result of it holds "regardless of the earlier iteration returned".
- The second parameter of cut back(), following the 2- to 4-paramater callback operate, is the initialValue (typically set to 0), which simply determines what the accumulator/previousValue used within the first iteration is. In different phrases (from fCC): Along with the callback operate, cut back() has a parameter which takes an preliminary worth for the accumulator. If this second parameter isn't used, then the primary iteration is skipped and the second iteration will get handed the primary aspect of the array because the accumulator.
*/


// 9. The discover() technique returns the primary aspect within the supplied array that satisfies the supplied testing operate. If no values fulfill the testing operate, undefined is returned.

const findDemoArr = [11, 20, 31, 40, 51]
const valFound = findDemoArr.discover(val => { return val % 2 === 0 }) 
console.log(valFound) // 20


// 10. The consists of() technique determines whether or not an array features a sure worth amongst its entries, returning true or false as applicable.

const includesDemoArr = [10, 20, 30, 40, 50]
console.log(includesDemoArr.consists of(20)) // true
console.log(includesDemoArr.consists of(25)) // false
console.log(includesDemoArr.consists of(2)) // false


// 11. The some() technique assessments whether or not no less than one aspect within the array passes the check applied by the supplied operate. It returns true if, within the array, it finds a component for which the supplied operate returns true; in any other case it returns false. It would not modify the array.

const someDemoArr = [10, 20, 30, 40, 50]
const thereIsAtLeastOne = someDemoArr.some(val => { return val > 12 && val < 28 })
console.log(thereIsAtLeastOne) // true


// 12. The each() technique assessments whether or not all components within the array move the check applied by the supplied operate. It returns a Boolean worth.

// Under are two examples of each().

const everyDemoArr1 = [10, 20, 30, 40, 50]
const theyAllPassTheTest1 = everyDemoArr1.each(val => { return typeof val === 'quantity' })
console.log(theyAllPassTheTest1) // true

const everyDemoArr2 = [10, 20, 30, 40, 50, 'I am a string, not a number']
const theyAllPassTheTest2 = everyDemoArr2.each(val => { return typeof val === 'quantity' })
console.log(theyAllPassTheTest2) // false


// 13. The kind() technique kinds the weather of an array in place and returns the sorted array. The default type order is ascending, constructed upon changing the weather into strings, then evaluating their sequences of UTF-16 code items values.

// Under are three examples of type().

const sortDemoArr1 = [100, 50, 32, 20000, 4]
sortDemoArr1.type()
console.log(sortDemoArr1) // [100, 20000, 32, 4, 50] // notice that the numbers have been sorted into ascending order in line with every quantity's first digit

const sortDemoArr2 = [100, 50, 32, 20000, 4]
sortDemoArr2.type((a, b) => { return a - b })
console.log(sortDemoArr2) // [4, 32, 50, 100, 20000] // notice that the numbers have been sorted into ascending order

const sortDemoArr3 = ['Tuesday', 'Wednesday', 'Monday', 'Friday', 'Thursday']
sortDemoArr3.type()
console.log(sortDemoArr3) // ['Friday', 'Monday', 'Thursday', 'Tuesday', 'Wednesday'] // notice that the times have been sorted into alphabetical order


// 14. The reverse() technique reverses an array in place. The primary array aspect turns into the final, and the final array aspect turns into the primary.

const reverseDemoArr = [10, 20, 30, 40, 50]
reverseDemoArr.reverse()
console.log(reverseDemoArr) // [50, 40, 30, 20, 10]


// 15. The fill() technique adjustments all components in an array to a static worth, from a begin index (default 0) to an finish index (default array.size). It returns the modified array.

// Under are three examples of fill().

const fillDemoArr1 = [10, 20, 30, 40, 50]
fillDemoArr1.fill(4) // fill all positions with 4
console.log(fillDemoArr1) // [4, 4, 4, 4, 4]

const fillDemoArr2 = [10, 20, 30, 40, 50]
fillDemoArr2.fill(7, 2) // fill with 7 from place 2
console.log(fillDemoArr2) // [10, 20, 7, 7, 7]

const fillDemoArr3 = [10, 20, 30, 40, 50]
fillDemoArr3.fill(8, 1, 4) // fill with 8 from place 1 till (not together with) place 4
console.log(fillDemoArr3) // [10, 8, 8, 8, 50]


// 16. The be part of() technique creates and returns a brand new string by concatenating all the components in an array (or an array-like object), separated by commas or a specified separator string. If the array has just one merchandise, then that merchandise shall be returned with out utilizing the separator.

const joinDemoArr = [10, 20, 30, 40, 50]
console.log(joinDemoArr.be part of()) // '10,20,30,40,50'
console.log(joinDemoArr.be part of('')) // '1020304050'
console.log(joinDemoArr.be part of(' ')) // '10 20 30 40 50'
console.log(joinDemoArr.be part of('-')) // '10-20-30-40-50'


// 17. The findIndex() technique returns the index of the primary aspect within the array that satisfies the supplied testing operate. In any other case, it returns -1, indicating that no aspect handed the check.

const findIndexDemoArr = [10, 20, 30, 40, 50]
const indexFound = findIndexDemoArr.findIndex(val => { return val > 32 })
console.log(indexFound) // 3


// 18. The indexOf() technique returns the primary index at which a given aspect may be discovered within the array, or -1 if it isn't current.

const indexOfDemoArr = [10, 20, 30, 40, 50]
const index = indexOfDemoArr.indexOf(30)
console.log(index) // 2


// 19. The slice() technique returns a shallow copy of a portion of an array into a brand new array object chosen from begin to finish (finish not included) the place begin and finish characterize the index of things in that array. The unique array won't be modified.

// Under are three examples of slice().

const sliceDemoArr1 = [10, 20, 30, 40, 50]
const sliced1 = sliceDemoArr1.slice(2, 4)
console.log(sliced1) // [30, 40]

const sliceDemoArr2 = [10, 20, 30, 40, 50]
const sliced2 = sliceDemoArr2.slice(0, 3)
console.log(sliced2) // [10, 20, 30]

const sliceDemoArr3 = [10, 20, 30, 40, 50]
const sliced3 = sliceDemoArr3.slice(2) // notice that if there isn't a second quantity handed to slice() (the second quantity signifies the sliceDemoArr3 index at which the "slicing" is to cease), then sliceDemoArr3.size is the de facto second quantity
console.log(sliced3) // [30, 40, 50]


// 20. The concat() technique is used to merge two or extra arrays. This technique doesn't change the prevailing arrays, however as a substitute returns a brand new array.

// Under are two examples of concat().

const concatDemoArr1 = [10, 20, 30, 40, 50]
const newConcatDemoArr1 = concatDemoArr1.concat(60)
console.log(newConcatDemoArr1) // [10, 20, 30, 40, 50, 60]

const concatDemoArr2 = [10, 20, 30, 40, 50]
const newConcatDemoArr2 = concatDemoArr2.concat([60, 70, 80, 90, 100])
console.log(newConcatDemoArr2) // [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
Enter fullscreen mode

Exit fullscreen mode

Add a Comment

Your email address will not be published. Required fields are marked *