# ES6 Javascript object and array II

Jan 8 · 8 min read

In this passage, we will mainly focus on those built-in array functions and several use cases.

1. reduce()

Execute the function for each element in array and accumulate them to be the final result

`Example 1let numbers = [1, 2, 3, 4, 5];let result = numbers.reduce(sum);//total - the value of last result//At the beginning, the total is 1 - 1st element in array, //and num is 2 - 2nd element array//Then the value of total will be 1 + 2 = 3, //and num will be 3 - 3rd element array//Then the value of total will be 1 + 2 + 3 = 6, //and num will be 4 - 4th element array//Then the value of total will be 1 + 2 + 3 + 4 = 10, //and num will be 5 - 5th element array//Then the value of total will be 1 + 2 + 3 + 4 + 5 = 15,//becoz this array got 5 elements only, so 15 will be the final //answerfunction sum(total, num) {  return total + num;}console.log(result);//output 15, becoz 1 + 2 + 3 + 4 + 5`

Another example

`let numbers = [100, 40, 30, 20, 10];let result = numbers.reduce(minus);function minus(total, num) {  return total - num;}console.log(result);//output 0, becoz 100 - 40 - 30 - 20 - 10`

Another example (with optional parameter for initial value)

`let numbers = [100, 40, 30, 20, 10];//300 is the initial value we given, //optional parameter of reduce functionlet result = numbers.reduce(minus, 300);//total - the value of last result//At the beginning, the total is the initial value we provide - 300//and num is 100 - 2nd element array//Then the value of total will be 300 - 100 = 200, //and num will be 30 - 3rd element array//Then the value of total will be 300 - 100 - 40 = 160, //and num will be 20 - 4th element array//Then the value of total will be 300 - 100 - 40 - 20 = 110, //and num will be 10 - 5th element array//Then the value of total will be 300 - 100 - 40 - 20 - 10 = 100,//becoz this array got 5 elements only, so 100 will be the final //answerfunction minus(total, num) {  return total - num;}console.log(result);//output 100, becoz 300 - 100 - 40 - 30 - 20 - 10`

2. filter()

Return an new array which including those element passed(return true) the filter function

`let numbers = [100, 40, 30, 20, 10];let result = numbers.filter(checking);//filter function, check whether number smaller than 100function checking(num) {  return num < 100;}console.log(result);//[40, 30, 20, 10]`

Another example

`let fruits = ['apple', 'orange', 'banana', 'kiwi'];let result = fruits.filter(checking);//check whether each fruit contains character 'i'function checking(fruit) {  return fruit.includes('i');}console.log(result);//['kiwi']//only 'kiwi' contains 'i'`

3. splice()

Add or remove element in existing array and return an new array containing the removed element

Remove element example — from the first element

`let fruits = ['apple', 'orange', 'banana', 'kiwi'];//2 parameters, the first one is which element by index to remove//the second parameter is how many element to be remove//In this example, start from index 0 to remove 1 elementlet removedElements = fruits.splice(0, 1);console.log(fruits);//['orange', 'banana', 'kiwi']console.log(removedElements);//['apple']`

Another example about remove element — from the last element

`let fruits = ['apple', 'orange', 'banana', 'kiwi'];//Let say we want to started from the last element, we can use //negative number in the first parameter//the last element is -1, vice versa//And the direction (of removing) is same as positive number //parameter//So, 'banana' and 'kiwi' will be remove instead of 'banana' and //'orange'let removedElements = fruits.splice(-2, 2);console.log(fruits);//['apple', 'orange']//-2 means the second last element, that means removed 'banana'console.log(removedElements);//['banana', 'kiwi']`

`let fruits = ['apple', 'orange', 'banana', 'kiwi'];//first 0, start from index 0//second 0, remove 0 element//'mango' - the new element we going to add, it will add to the //first element (according to first param)fruits.splice(0, 0, 'mango');console.log(fruits);//['mango', 'apple', 'orange', 'banana', 'kiwi']`

`let fruits = ['apple', 'orange', 'banana', 'kiwi'];//first 1, start from index 1 (second element)//second 1, remove one element//'mango', 'pineapple' - the new element we going to addfruits.splice(1, 1, 'mango', pineapple);console.log(fruits);//['apple', 'banana', 'kiwi', 'orange', 'banana', 'kiwi']`

4. slice()

Copy selected elements by start and end index to new array

`let fruits = ['apple', 'orange', 'banana', 'kiwi'];//first parameter, start from index 1 (second element)//second parameter, end at index 3(fourth element), but not //including itvar someFruits = fruits.slice(1, 3);console.log(someFruits);//['orange', 'banana']`

Another example, using negative index

`let fruits = ['apple', 'orange', 'banana', 'kiwi'];//first parameter, start from index -3 (second element)//second parameter, end at index 3(fourth element), but not //including it//And the direction (of removing) is same as positive number //parameter//So the second parameter always larger than the first parameter//In this case, the last 3rd element is 'orange' and end at the last //2nd element (but not including it), so only 'orange' will be //copyvar someFruits = fruits.slice(-3, -2);console.log(someFruits);//['orange']`

Another example, with no parameter

`let fruits = ['apple', 'orange', 'banana', 'kiwi'];//by default, if we left empty, 1st parameter will be 0//for the 2nd parameter, if we left empty, will be the end of array//that means in this case we will copy everything from the arrayvar someFruits = fruits.slice();console.log(someFruits);//['apple', 'orange', 'banana', 'kiwi']`

5. concat()

Append the elements of other arrays at the end and return the new result in new array.

`let fruits = ['apple', 'orange', 'banana', 'kiwi'];let snacks = ['chips', 'candy', 'chocolate', 'mints'];//always returns new array, existing arrays not affectedlet food = fruits.concat(snacks);console.log(food);//['apple', 'orange', 'banana', 'kiwi', 'chips', 'candy', 'chocolate', 'mints']`

6. find()

Similar with filter(), but it stop searching once the first return found

`let fruits = ['apple', 'orange', 'banana', 'kiwi'];let result = fruits.find(findFunc);//filter function, check whether number smaller than 100function findFunc(fruit) {  return fruit.includes('a');}console.log(result);//apple//apple, orange, banana also contain 'a', but since 'apple' locate //at the first index, so return 'apple'`

7. findIndex()

Similar with find(), searching from each array element and stop searching once the first return found, but returns index number instead of value

`let fruits = ['apple', 'orange', 'banana', 'kiwi'];let result = fruits.findIndex(findFunc);//filter function, check whether number smaller than 100function findFunc(fruit) {  return fruit.includes('a');}console.log(result);//0//As apple located at the first index`

8. Object.assign()

Copy properties from one or multi objects to another object. No new array would return, only add/overwrite to the target object (1st parameter)

`const fruitsCount = { kiwi: 1, banana: 2 };const snacksCount = { candy: 4, chocolate: 9 };//1st parameter is the target object, all properties in 2nd and//other parameter will be copy to the 1st parameter//In this case, the properties from snacksCount will be copy to //fruitsCountObject.assign(fruitsCount, snacksCount);console.log(fruitsCount);// {kiwi: 1, banana: 2, candy: 4, chocolate: 9}console.log(snacksCount);// {candy: 4, chocolate: 9}`

Another example

`const fruitsCount = { kiwi: 1, banana: 2 };const snacksCount = { candy: 4, chocolate: 9, banana: 3 };const vegeCount = { eggPlant: 7, banana: 5};//1st parameter is the target object, all properties in 2nd and//other parameter will be copy to the 1st parameter//In this case, the properties from snacksCount and vegeCount will //be copy to fruitsCount//If multi parameter got the same properties ('banana' in this //case), then the properties from "later" parameter will be apply//In this case, 'banana: 5' from vegeCount will apply instead of //'banana: 3' from snacksCountObject.assign(fruitsCount, snacksCount, vegeCount);console.log(fruitsCount);{kiwi: 1, banana: 5, candy: 4, chocolate: 9, eggPlant: 7}console.log(snacksCount);// {candy: 4, chocolate: 9, banana: 3}console.log(vegeCount);// {eggPlant: 7, banana: 5}`

9. IndexOf

Lookup the index in array by element value, if more than one array element got same value, then it will return the index of the first element

`let fruits = ['apple', 'orange', 'banana', 'kiwi'];let index = fruits.indexOf('orange');console.log(index);//return 1`

10. push

Add new element to the last index of existing array

`let fruits = ['apple', 'orange', 'banana', 'kiwi'];fruits.push('cherry');console.log(fruits);//['apple', 'orange', 'banana', 'kiwi', 'cherry']`

11. pop

Remove last element from existing array

`let fruits = ['apple', 'orange', 'banana', 'kiwi'];fruits.pop();console.log(fruits);//['apple', 'orange', 'banana']`

12. shift

Remove the first element from existing array

`let fruits = ['apple', 'orange', 'banana', 'kiwi'];fruits.shift();console.log(fruits);//['orange', 'banana', 'kiwi']`

13. unshift

Add new element to the first of array

`let fruits = ['apple', 'orange', 'banana', 'kiwi'];fruits.shift('cherry');console.log(fruits);//['cherry', 'apple', 'orange', 'banana', 'kiwi']`

Some common use case

1. Removing duplicate element

By filter()

`let duplicate_array = ['apple', 'orange', 'orange', 'banana', 'banana', 'kiwi', 'banana'];let filtered_array = duplicate_array.filter(function(element, index) {return index === duplicate_array.indexOf(element); })console.log(filtered_array);//['apple', 'orange', 'banana', 'kiwi']`

By Array.from() and Set

`let duplicate_array = ['apple', 'orange', 'orange', 'banana', 'banana', 'kiwi', 'banana'];//Automatically removes duplicate elementsconst set = new Set(duplicate_array);let filtered_array = Array.from(set);console.log(filtered_array);//['apple', 'orange', 'banana', 'kiwi']`

2. Finding duplicate elements

By reduce() and indexOf()

`let duplicate_array = ['apple', 'orange', 'orange', 'banana', 'banana', 'kiwi', 'banana'];function sum(list, element, index) {//just keep in mind that the default index is 1, becoz the total is //the value of 1st element. However, if we added the optional //parameter - initial value, the index will be 0 (the 1st index in //array)let duplicated = index !== duplicate_array.indexOf(element);if (duplicated && list.indexOf(element) < 0)    {        list[list.length] = element    }return list;    }let duplicated_list = duplicate_array.reduce(sum, []);console.log(duplicated_list);//['orange', 'banana']`

3. Copying array with nested array

As the state management in React.JS and Redux always require immutable state value, so instead of update the current object, we often create the new one and copy the value in order to meet the standard. (For the reason of immutable state, please refer to another passage)

`const fruits = ['kiwi', 'banana'];const snacks = ['candy', 'chocolate'];const drink = ['beer', 'coke'];let food = [fruits, snacks];let all = [food, drink];//only copy the reference addresslet copy_all = allall.push('new_item');//both 'all' and 'copy_all' show the new value, that means we copied //the object reference onlyconsole.log(all);console.log(copy_all);copy_all = [..all];all.push('new_item2');//array 'all' reflects new value, array 'copy_all' doesn't, that //means we copied the value, not referenceconsole.log(all);console.log(copy_all);//try to add new value 'new_item3' to the nested arrayall[0].push('new_item3');//both 'all' and 'copy_all' show the new value, that means for the //nested array we copied the object reference only//we realize that each array/ nested array have to be copied //'manually'//the final resultcopy_all = [[[...all[0][0]], [...all[0][1]]], [...all[1]]];console.log(copy_all);`

The following array built-in function would edit the existing array, so you may avoid to use them when editing the state of React.JS / Redux

splice()
Object.assign()
push()
pop()
shift()
unshift()

## Analytics Vidhya

Analytics Vidhya is a community of Analytics and Data…

## Analytics Vidhya

Analytics Vidhya is a community of Analytics and Data Science professionals. We are building the next-gen data science ecosystem https://www.analyticsvidhya.com