JS: Operations with Array: retrieve, add, update, delete

//* Operations with Array *// 16-sep-2022


//1) retrieve elements from array

//                              0            1             2
let vegetables = ['tomato', 'potato', 'spinach']

console.log(vegetables)
console.log(vegetables[0])
console.log(vegetables.at(0))
console.log(vegetables.at(2))


//2) add element to array

let f1 = vegetables.push('brinjal') // adds element at end
console.log(f1) // returns new length of array
console.log(vegetables) // returns updated array

// updated array --> ['tomato', 'potato', 'spinach', 'brinjal]

let f2 = vegetables.unshift('cabbage') // adds element at start
console.log(f2) // returns new length of array
console.log(vegetables) // returns updated array

// updated array --> ['cabbage', tomato', 'potato', 'spinach', 'brinjal]


//3) update element of array

//                      0         1         2           3          4        5
let colors = ['white', 'red', 'yellow', 'green', 'pink', 'blue']

let f3 = colors[0] = 'black' // updates element at 0 index
console.log(f3) // returns updated element
console.log(colors) // returns updated array

// updated array --> ['black', 'red', 'yellow', 'green', 'pink', 'blue']


//4) delete elemetns of array

let f4 = colors.pop() // remoeves last element
console.log(f4) // returns deleted/removed element
console.log(colors) // returns updated array

// updated array --> ['black', 'red', 'yellow', 'green' 'pink']

let f5 = colors.shift() // removes first element
console.log(f5) // returns deleted/removed element
console.log(colors) // returns updated array

// updated array --> ['red', 'yellow','green', 'pink']

let f6 = colors.splice(0,1) // removes 1 element from 0 index
console.log(f6) // returns deleted/removed element
console.log(colors) // returns updated array

// updated array --> ['yellow', 'green' 'pink']

let f7 = colors.splice(0,2) // removes 2 elements from 0 index
console.log(f7) // returns deleted/removed element
console.log(colors) // returns updated array

// updated array --> ['pink']


// 3) update element of array // example 2

//                     0          1           2
let names = ['ram', 'laxman', 'sita']

names[0] = 'sham'
console.log(names)

// updated array --> ['sham', 'laxman', 'sita']

names[1] = 'krishna'
console.log(names)

// updated array --> ['sham', 'krishna', 'sita']

Comments

Popular posts from this blog

What is IP and TCP - Marathi

JS - Day 1

JS - basic types and ways of writing function