Arrays and Objects (JavaScript)

Arrays and Objects (JavaScript)

Working with Data in JavaScript - A Deep Dive into Arrays and Objects

In Javascript when it comes to handling and managing the data we use arrays and objects are two core data structures which we should know to master in javascript so let us dive in.

JavaScript Array 101

An array data structure stores multiple values in a single and ordered list. Each value has an index and making it easy to access and manipulate elements in various ways.

→ Declaration

let fruits1 = ['apple', 'banana', 'cherry'];

let fruits2 = new Array('apple', 'banana', 'cherry'); // new way to declare array in js (array constructor)

→ Accessing and modifying elements

console.log(fruits1[0]); // apple
fruits1[2] = 'orange';
console.log(fruits1) // ['apple', 'banana', 'orange']

→ Common array methods

  • push() → Adds a new element at the end of an array.

  • pop() → Removes the last element from an array.

  • unshift() → Inserts a new element at the beginning of an array.

  • shift() → Removes the first element of an array.

  • map() → Transforms each element in an array and returns a new array.

  • filter() → Returns a new array containing elements that meet a specific condition.

reduce() → Accumulates array elements into a single value based on a reducer function.

Example →

const fruits = ['apple', 'banana', 'cherry'];
fruits.push('orange'); 
// fruits = ['apple', 'banana', 'cherry', 'orange']

Understanding Objects in JavaScript

While arrays store sequential data whereas objects allow you to store data in key - value pairs.

→ Declaration

const person = {
  name: 'Aryan Sinha',
  age: 23,
  hobbies: ['coding', 'reading', 'gaming']
};

const anotherPerson = new Object(); // new way to declare object in js (object constructor)
anotherPerson.name = 'Ashi Singh';
anotherPerson.age = 23;

→ Accessing and modifying elements

console.log(person.name); // Aryan Sinha
console.log(person['age']); // 23
person.age = 24;
person.location = 'Patna';
delete person.hobbies;

→ Use case examples

const users = [
  { name: 'Aryan Sinha', age: 23, hobbies: ['coding', 'reading', 'gaming'] },
  { name: 'Ashi Singh', age: 23, hobbies: ['reading', 'cooking', 'coding'] }
];

Looping Over Arrays and Objects

Looping over arrays

→ for

const fruits = ['apple', 'banana', 'orange'];
for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}

→ forEach()

fruits.forEach(fruit => console.log(fruit));

→ for of

for (const fruit of fruits) {
  console.log(fruit);
}

Looping over objects

→ for in

const person = { name: 'Aryan Sinha', age: 23, location: 'Patna' };
for (const key in person) {
  console.log(`${key}: ${person[key]}`);
}

→ Object.keys() and Object.value()

Object.keys(person).forEach(key => {
  console.log(`${key}: ${person[key]}`);
});

console.log(Object.values(person));

→ Object.entries()

for (const [key, value] of Object.entries(person)) {
  console.log(`${key}: ${value}`);
}

Visual Representation of Arrays and Objects

→ Arrays

const fruits = [ 'apple', 'banana', 'orange'];

→ Objects

let person = {
  'name': 'Aryan Sinha',
  'age': 23,
  'hobbies': ['coding','reading', 'gaming'],
  'location': {
    'city': 'Patna',
    'country': 'India',
  }
}

Example of map, filter and reduce

→ map() → Transforms each element.

→ filter() → Retains only elements that match a condition.

→reduce() → Accumulates the filtered elements into a single value.

// Starting array
const numbers = [1, 2, 3, 4];

const mappedNumbers = numbers.map(num => num * 2); // use map() to multiply each number by 2
// mappedNumbers is now [2, 4, 6, 8]

const filteredNumbers = mappedNumbers.filter(num => num > 3); // use filter() to keep numbers greater than 3
// filteredNumbers is now [4, 6, 8]

const sum = filteredNumbers.reduce((acc, num) => acc + num, 0); // use reduce() to sum all the filtered numbers
// sum is 18

console.log(`After map: ${mappedNumbers}`); // [2, 4, 6, 8]
console.log(`After filter: ${filteredNumbers}`); // [4, 6, 8]
console.log(`After reduce: ${sum}`); // 18

Conclusion

Arrays and objects are essential for organizing and manipulating data in javascript. Arrays provide an ordered list of items with powerful built - in methods while objects store data using key - value pairs to model more complex entities.

Thanks for reading this far.