# Sujay Kundu

Full Stack Web Developer

Posted by : at

Category : javascript #### Merging two Arrays using Spread Operator :

Note: This will concatenate the two Arrays:

``````const arr1 = [1,2,3];
const arr2 = [3,4,5];
const arr3 = [...arr1, ...arr2]; // arr3 ==> [1,2,3,3,4,5]
``````

Don’t forget, one can do this too

``````const a = [1, 2, 3]
const b = [...a, 4] // b ==> [1, 2, 3, 4]
``````

#### Creating a unique Array using Sets :

This will create a new array with unique values

``````let numberArray = [1,1,4,5,4,4,2,1,5];
let uniqueNumberArray = [...new Set(numberArray)];
// uniqueNumberArray ==> [1 ,4 ,5 ,2]
``````

#### Get new Unique Object Array using Set and Map :

``````let oldArray = [
{
"id": 11 ,
"name": "sujay"
},
{
"id": 213,
"name": "sujay"
},
{
"id":11,
"name": "sujay"
}
];

console.log(oldArray);

// Now returning the unique objects of that array
const newUniqueArray = Array.from(new Set(oldArray.map(item => item.id)))
.map(id => {
return oldArray.find(item => item.id === id)
})

console.log('new unique array', newUniqueArray);
// new unique array
[
{
"id": 213,
"name": "sujay"
},
{
"id":11,
"name": "sujay"
}
]
``````

### For Loop

The `for` loop is one of the most basic loops for looping through an array. It takes a starting index and then loops through to the ending index. Index must be an integer.

Example:

``````const array = [1,2,3];

for (let i = 0; i < array.length; i++)
{
console.log(i);
}
``````

The loop above should log all the numbers in the array.

Indexes do not have to be consecutive:

``````const array = [1,2,3];
for (let i = 0; i < array.length; i+=2)
{
console.log(i);
}
``````

The loop above will skip every second number.

### While Loop

`while` loop will loop whenever a condition stays true.

For example, the loop below will run if the index number `i` is less than three:

``````const array = [1,2,3];
let i = 0;
while(i < array.length)
{
console.log(i);
}
``````

If the condition in the parentheses is never true, then the loop content will never run.

### Do While Loop

`do...while` loop will always execute the first iteration.

``````const array = [1,2,3];
let i = 0;
do{
console.log(i);
}
while(i < array.length)
``````

In the example above, it will at least log 0, but it will also log 1 and 2 in this case since those two numbers are less than three.

With the above loops, you can call `break` to stop the loop or `return` before the loop is completely finished.

``````//do while loop
const array = [1,2,3];
let i = 0;
do{
console.log(i);
if (i == 1}
{
break;
}
}while(i < array.length)
//while loop
i = 0;
while(i < array.length)
{
if (i == 1)
{
break;
}
console.log(i);
}
//for loop
for (let j = 0; j < array.length; j++)
{
if (j == 1)
{
break;
}
console.log(j);
}
``````

In the above examples, you will not see two logged.

An example of returning from within the loop:

``````const loop = ()=>{
const array = [1,2,3];
for (let j = 0; j < array.length; j++){
if (j == 1){
return j;
}
console.log(j);
}
}loop() //returns 1
``````

You can also skip iterations with `continue` statement:

``````const array = [1,2,3];for (let j = 0; j < array.length; j++){  if (j == 1){    continue;  }  console.log(j) // 1 will be skipped;}
``````

### Array.forEach

`forEach` will iterate through every entry of the array. You cannot break out of it or return a value from it. It takes a callback function where you can execute code.

Example:

``````const array = [1,2,3];  array.forEach(a =>{  console.log(a);})
``````

In the above example, all the numbers in the array will be logged.

### Array.find

`Array.find` will return the element in the array with the given condition. For example, if you want to get certain numbers from the array, you do:

``````const array = [1,2,3];
const num = array.find(a => a == 2);// returns 2
``````

`find` returns a single result.

### Array.findIndex

`Array.findIndex` will return the index of the element in the array with the given condition. It takes a callback function that returns a given condition. For example, if you want to get the index of a certain numbers from the array, you do:

``````const array = [1,2,3];const num = array.findIndex(a => a == 2); // returns 1
``````

### Array.filter

`Array.filter` will return an array of items that meet the given condition. It takes a callback function that returns a given condition. `filter` returns a new array.

For example, if you want to get the index of a certain numbers from the array, you do:

``````const array = [1,2,3];
const numArray = array.filter(a => a == 2); // returns 
``````

### Array.includes

`Array.includes` checks if an item exists in an array. It takes a number or string which the function can compare.

``````const array = [1,2,3];
const includesTwo = array.includes(2); // returns true
``````

## Array.some

`Array.some`checks if some items meet the condition given. It takes a callback function which returns a boolean for the condition.

``````const array = [1,2,3];
const includesTwo = array.some(a => a == 2); // returns trueconst includesFive = array.some(a => a == 5); // returns false
``````

## Array.every

`Array.every` checks if every item meet the condition given. It takes a callback function which returns a boolean for the condition.

``````const array = [1,2,3];
const everyElementIsTwo = array.every(a => a == 2); // returns falseconst everyElementIsNumber = array.every(a => typeof a == 'number'); // returns true since every item in the array is a number
``````

### Array.isArray

`Array.isArray` checks if an object given is an array. It is a convenient way to check if an element is an array.

``````const array = [1,2,3];
const notArray = {};
let objIsArray = Array.isArray(array); // trueobjIsArray = Array.isArray(notArray); // false
``````

### Array.from(new Set(array))

`Set` is a object that cannot have duplicate entries. You can create a new `Set`from an array then convert it back to an array.

``````const array = [1,2,2,3];
const arrayWithDups = Array.from(new Set(array)); //returns new array without duplicates, [1,2,3]
``````

### Array.slice(startIndex, endIndex)

Returns a new array from `startIndex` to `endIndex — 1` .

Example:

``````const arr = [1,2,3,4,5];
const newArr = arr.slice(0,2);
console.log(newArr); // returns [1,2]
``````

### Array.splice(index, numberOfItems)

Remove array item in place with the given `index`, and then `numberOfItems`after it.

For example:

``````const arr = [1,2,3,4,5];
arr.splice(0,2);
console.log(arr); // returns [3, 4, 5] since we specified that we remove item located at index 0 and 2 items after that.
``````

### Array.sort(sortFunction)

`Array.sort` sorts array in place according to the condition you return in`sortFunction` .

The `sortFunction` should be in this format:

``````const sortFunction = (a, b) {
if (a < b) {
return -1;
}
if (a > b) {
return 1;
}  // a must be equal to b  return 0;
}
``````

By default, if no `sortFunction` is specified, then the array items will be converted to string and will be sorted according to the Unicode value of the string.

### Array.fill(newElement, startIndex, endIndex)

`Array.fill` will add or replace the element with the element specified from `startIndex` to `endIndex` . If no `startIndex` is defined then it will start from 0. If no `endIndex` is defined, then it will change values up to the end of the array.

For example:

``````let array = [1, 2, 3, 4, 5];
console.log(array.fill(0, 2, 4));
// array is now [1, 2, 0, 0, 0]
console.log(array.fill(5, 1));// array is now [1, 5, 5, 5, 5]
console.log(array.fill(6));// array is now [6, 6, 6, 6, 6]
``````

#### Recursively Flatten Array

`Array.flat` function does not do a good job of recursively flatten arrays. The depth is limited and it does not flatten all kinds of nested array structures. The better way to do it is to write a recursive function to do it.

``````let arr1 = [1, 2, [3, 4], 5];
let arr2 = [1, 2, [3, 4], [5, [6,[7,]]]];
const flatten = (items) => {  const flat = [];
items.forEach(item => {
if (Array.isArray(item)) {
flat.push(...flatten(item));
} else {
flat.push(item);
}
});
return flat;
}
console.log(flatten(arr1));
console.log(flatten(arr2));
``````

### Array.join(separator)

`Array.join` will return a string by concatenating the entries after they are converted to string with `separator` between each entry. Works best with string and number arrays.

Example:

``````const arr = [1,2,3];
console.log(arr.join(',')) // get '1,2,3'
const arr = ['1',2,3];
console.log(arr.join(',')) // get '1,2,3'
``````

### Array.indexOf(elementToFind)

`Array.indexOf`will return the first index of the `elementToFind` in the array. Works best with string and number arrays. If you want to find a non-string or number object, use `Array.findIndex` . Returns -1 is element is not found.

Example:

``````const arr = [1,2,3];
console.log(arr.indexOf(1)); // returns 0
const arr2 = [1,1,2,3];
console.log(arr2.indexOf(1)) // still 0
``````

# Array.lastIndexOf()

`Array.lastIndexOf`will return the last index of the `elementToFind` in the array. Works best with string and number arrays. Returns -1 is element is not found. The function also takes a starting index to start searching backwards as a second parameter

Example:

``````const arr = [1,2,3];
console.log(arr.indexOf(1)); // returns 0
const arr2 = [1,1,2,3];
console.log(arr2.indexOf(1)) // returns 1
const arr3 = [3,1,2,3]
console.log(arr3.lastIndexOf(3, 2)) // returns 0, start searching backwards from index 2
``````

### Array.push(newElement)

`Array.push` adds a new element to an array.

Example:

``````let arr = [1,2,3];
arr.push(4);
console.log(arr) // [1,2,3,4]
``````

### Array.pop()

`Array.pop` removes the last element of the array.

Example:

``````let arr = [1,2,3,4];
arr.pop();
console.log(arr) // [1,2,3]
``````

### Array.map(mapFunction)

`Array.map` returns a new array which transforms the existing array’s element by calling the `mapFunction` . `mapFunction` takes one argument, which is the array element.

Example:

``````let arr = [1,2,3,4];
const newArr = arr.map(a=>a*2)
console.log(newArr) // [2,4,6,8]
``````

### Array.reduce(reduceFunction)

`Array.reduce` combines elements of an array to return a value by calling the `reduceFunction` on all the elements to combine them. `reduceFunction` takes 2 arguments, which is the current and next element in the array.

Example:

``````const arr = [1,2,3,4];
const sum = arr.reduce((a,b)=>a+b);
console.log(sum); // returns 10
``````

### Array.reverse()

`Array.reverse` returns a new array with the existing array’s elements in reverse order.

Example:

``````const arr = [1,2,3,4];
console.log(arr.reverse()) // [4,3,2,1]
``````
Categories