Showing posts with label Array. Show all posts
Showing posts with label Array. Show all posts

Friday, May 12, 2023

Push into an Array in JavaScript


let myarray = [1,2,3,4,5]


// Add to the start of an array

Array.unshift(element);

myarray.unshift(100); // output 100,1,2,3,4,5


// Add to the end of an array

Array.push(element);

myarray.push(100); // output 1,2,3,4,5,100



// Add to a specified location

Array.splice(start_position, 0, new_element...);

myarray.splice(2, 0, 100,200); // output 1,2,100,200,3,4,5



// Add with concat method without mutating original array

let newArray = [].concat(element);

let newmyarray = myarray.concat(10,20);


Tuesday, October 6, 2020

Sort JSON Array with Value

Example:Sort JSON Array

Thursday, July 16, 2020

Sort JSON object Array

Sort JSON object Array



Thursday, January 23, 2020

Simple JaveScript Tricks with Array and Object

Combining Multiple Objects

Consider you have three different objects:
const obj1 = {'No': 1, 'firstname': 'Rakesh'};
const obj2 = {'lastname': 'Patel'};
const obj3 = {'Sex': 'Male','progLang':['.Net','MVC','SharePoint']};

combine all the above 3 object into another object:

const objCombined = {...obj1, ...obj2, ...obj3};

The '…' is the spread operator. You can read more about this in the MDN Web Docs

Check if an object is an array

const obj = {data: 1};
const arr = [1, 2, 3];

Array.isArray(obj);  // false
Array.isArray(arr);  // true

Rest parameter syntax

A function that accepts any number of arguments. There is a special syntax called the rest parameter syntax to create such a function.

Example 1:

function test(...values) {
    console.log(values);
}
test(1);
test(1, 2);
test(1, 2, 3);
test(1, 2, 3, 4);

output:
[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]

you can even pass object as a arguments

Example 2:

function sum(...values) {
    let sum = 0;
    for (let i = 0; i < values.length; i++) {
        sum += values[i];
    }
  
    return sum;
}

console.log(sum(1));
console.log(sum(1, 2));
console.log(sum(1, 2, 3));
console.log(sum(1, 2, 3, 4));

output:
1
3
6
10