Topic 5: JS Operations with Array

//Revision Lecture 7: 1 Oct 2022

//Topic 5: //* Operations with Array *//


//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(vegetables) // returns updated array

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

let f2 = vegetables.unshift('cabbage') // adds element at start
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(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(colors) // returns updated array


let f5 = colors.shift() // removes first 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(colors) // returns updated array

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

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

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



// more examples:

//1) update element of array 

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

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

// updated array --> ['ram', 'ravan', 'sita']

names[2] = 'hanuman'
console.log(names)

// updated array --> ['ram', 'ravan', 'hanuman']


//2) add element to array

names.push('dashrath')
console.log(names)

// updated array --> [ 'ram', 'ravan', 'hanuman', 'dashrath' ]

names.unshift('sugriv')
console.log(names)

// updated array --> [ 'sugriv', 'ram', 'ravan', 'hanuman', 'dashrath' ]


//3) delete/remove element from array

names.pop()
console.log(names)

// updated array --> [ 'sugriv', 'ram', 'ravan', 'hanuman' ]

names.shift()
console.log(names)

// updated array --> [ 'ram', 'ravan', 'hanuman' ]

names.splice(0,2)
console.log(names)

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

टिप्पण्या