Playing around with array methods in JavaScript
const exampleText = "A nut for a jar of tuna"
const textArray = exampleText.split(" ")
ForEach¶
As far as I understand it, forEach is just different syntax for a for loop. It doesn't return anything and is useful for things like logging to the console.
function toUpperCase(el, idx, arr) {
return el.toUpperCase()
}
var upperCase = textArray.forEach(toUpperCase)
console.log(upperCase)
function printString(el, idx, arr) {
console.log(`${idx} ${el}`)
}
textArray.forEach(printString)
Map¶
Map returns values - it maps arrays from some value to another value. As with all of these functions, it only applies to arrays and not objects.
var upperCase = textArray.map(toUpperCase)
console.log(upperCase)
Cool.
Reduce¶
Reduce takes array items and groups them together back into a single variable.
function reverseString(accumulator, el, idx, arr) {
return el + ' ' + accumulator
}
var reverseStr = textArray.reduce(reverseString, '')
console.log(reverseStr)
Join¶
Since we're reducing to a String we could also be using join here:
textArray.join('')
Reverse¶
We can have the same effect as the reduce function by doing the following:
textArray.reverse().join(' ')
You need to be careful as reverse is applied in place so affects all our code referring to textArray from now on.
textArray
Let's just put it back to how it was before
textArray.reverse()
Filter¶
function isThreeLetters(el, idx, arr) {
return el.length === 3
}
var threeLetterWords = textArray.filter(isThreeLetters)
console.log(threeLetterWords)
The above example is a more explicit description of whats going on, but it could be written in a more simplified way:
var threeLetterWords = textArray.filter(word => word.length === 3)
Concat¶
Pretty simple - concatenates arrays. Get's more interesting when dealing with nested arrays.
[1,2,3].concat(4)
[1,2,3].concat([4,5])
Concatentation only pulls sub-elements out of an another array up to a depth of 1, otherwise it just concatenates the array itself.
[1,2,3].concat([[4], [[5, 6]]])
Reduce and Concat (Flat)¶
flat is currently in experimental stages and not supported by Node. The suggested replacement is a reduce followed by a concat. flat function logic is really useful for dealing with nested arrays, pulling out sub-elements and putting them all at the same depth.
First let's set up a shallow nested array:
function nestArrays(el) {
return Array.from(el).map(toUpperCase)
}
var nestedChars = textArray.map(nestArrays)
console.log(nestedChars)
Now write some code to flatten the nested array:
function concatenate(acc, el) {
return acc.concat(el)
}
var unNestedChars = nestedChars.reduce(concatenate, [])
The above can be simplified to:
var unNestedChars = nestedChars.reduce((acc, el) => acc.concat(el), [])
console.log(unNestedChars)
unNestedChars.reverse().join(' ')
Surprise! Palindrome!
The above example works for a depth of 1. How about an even more nested array?
Now we create a deeply nested array:
function deepNest(acc, el) {
return [acc, Array.of(el)]
}
var deepNestedChars = textArray.reduce(deepNest, [])
console.log(deepNestedChars)
The problem can be solved neatly using recursion, introducing the Array.isArray function:
function flattenDeep(nestedChars) {
return nestedChars.reduce((acc, el) => Array.isArray(el) ? acc.concat(flattenDeep(el)) : acc.concat(el), [])
}
console.log(flattenDeep(deepNestedChars))
Reversing the Palindrome¶
Using what the above to try a few different methods of reversing the palindrome from the array of words:
textArray
The simplest way I can think of is joining it back into a string (without spaces) then making an array of chars and reversing:
Array.from(textArray.join('')).reverse().join('')
More complicated is a map-reduce type example: reversing each word during a map step and then joining them back together again in reverse in a reduce step.
var reversedText = textArray.map(el => Array.from(el).reverse())
reversedText
reversedText.reduce((acc, el) => [el.concat(acc).join('')], [])
This is definitely awkward and overcomplicated in loads of ways but I just wanted to mess around with putting the logic purely inside map and reduce functions.