Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Essential JavaScript Array and Object Methods

Tech May 9 3

Essential JavaScript Array and Object Methods

Array Manipulation Methods

splice()

The splice() method modifies an array by removing or replacing existing elements and/or adding new elements in place.


const fruitCollection = ["apple", "banana", "cherry", "date"];
// Insert "fig" at position 2 without removing any elements
const extracted = fruitCollection.splice(2, 0, "fig");
// fruitCollection is now ["apple", "banana", "fig", "cherry", "date"]
// extracted is an empty array since no elements were removed
console.log("After insertion:", fruitCollection);

// Remove 1 element at position 3
const removedItem = fruitCollection.splice(3, 1);
// fruitCollection is now ["apple", "banana", "fig", "date"]
// removedItem is ["cherry"]
console.log("After removal:", fruitCollection, "Removed:", removedItem);

// Replace 1 element at position 2 with "grape"
const replaced = fruitCollection.splice(2, 1, "grape");
// fruitCollection is now ["apple", "banana", "grape", "date"]
// replaced is ["fig"]
console.log("After replacement:", fruitCollection, "Replaced:", replaced);

// Remove multiple elements starting from position 1
const multipleRemoved = fruitCollection.splice(1, Number.MAX_VALUE);
// fruitCollection is now ["apple"]
// multipleRemoved is ["banana", "grape", "date"]
console.log("Final array:", fruitCollection, "Removed items:", multipleRemoved);

push()

The push() method adds one or more elements to the end of an array and returns the new length.


const numberList = [10, 20, 30];
numberList.push(40); // numberList is now [10, 20, 30, 40]
console.log("After push:", numberList);

// Adding multiple elements
numberList.push(50, 60, 70); // numberList is now [10, 20, 30, 40, 50, 60, 70]
console.log("After multiple pushes:", numberList);

pop()

The pop() method removes the last element from an array and returns that element.


const stack = [1, 2, 3, 4, 5];
const lastElement = stack.pop(); // lastElement is 5, stack is [1, 2, 3, 4]
console.log("Popped element:", lastElement);
console.log("After pop:", stack);

shift()

The shift() method removes the first element from an array and returns that element.


const queue = ["first", "second", "third"];
const firstElement = queue.shift(); // firstElement is "first", queue is ["second", "third"]
console.log("Shifted element:", firstElement);
console.log("After shift:", queue);

unshift()

The unshift() method adds one or more elements to the beginning of an array and returns the new length.


const tasks = ["complete project", "review code"];
tasks.unshift("plan project", "gather requirements"); 
// tasks is now ["plan project", "gather requirements", "complete project", "review code"]
console.log("After unshift:", tasks);

Object Methods

hasOwnProperty()

The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property.


const userProfile = {
  name: "Alex",
  age: 30,
  email: "alex@example.com"
};

console.log("Has name property:", userProfile.hasOwnProperty("name")); // true
console.log("Has address property:", userProfile.hasOwnProperty("address")); // false
console.log("Has inherited property:", userProfile.hasOwnProperty("toString")); // false

String Methods

match()

The match() method retrieves the result of matching a string against a regular expression.


const sampleText = "JavaScript is versatile. JavaScript is powerful. JavaScript is everywhere.";
// Case-insensitive global search for "javascript"
const regex = /javascript/gi;
const matches = sampleText.match(regex);
console.log("Found matches:", matches); // ["JavaScript", "JavaScript", "JavaScript"]
console.log("Number of matches:", matches.length); // 3

// Extracting numbers from a string
const mixedString = "Order 123 and item 456 are in stock.";
const numberPattern = /\d+/g;
const numbers = mixedString.match(numberPattern);
console.log("Extracted numbers:", numbers); // ["123", "456"]

Array Iteration Methods

map()

The map() method creates a new array populated with the results of calling a provided function on every element.


const originalValues = [1, 2, 3, 4, 5];
const transformedValues = originalValues.map(item => item * 2);
console.log("Original:", originalValues);
console.log("Doubled:", transformedValues); // [2, 4, 6, 8, 10]

// Transforming objects in an array
const users = [
  { id: 1, name: "Alice" },
  { id: 2, name: "Bob" },
  { id: 3, name: "Charlie" }
];

const userIds = users.map(user => user.id);
console.log("User IDs:", userIds); // [1, 2, 3]

reduce()

The reduce() method executes a reducer function on each element of the array, resulting in a single output value.


const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => {
  console.log(`Accumulator: ${accumulator}, Current: ${currentValue}`);
  return accumulator + currentValue;
}, 0);
console.log("Total sum:", sum); // 15

// Calculating product
const product = numbers.reduce((acc, val) => acc * val, 1);
console.log("Product:", product); // 120

// Counting occurrences
const fruits = ["apple", "banana", "apple", "orange", "banana", "apple"];
const fruitCount = fruits.reduce((count, fruit) => {
  count[fruit] = (count[fruit] || 0) + 1;
  return count;
}, {});
console.log("Fruit count:", fruitCount); // { apple: 3, banana: 2, orange: 1 }

filter()

The filter() method creates a new array with all elements that pass the test implemented by the provided function.


const scores = [85, 92, 76, 88, 95, 60, 72];
const passingScores = scores.filter(score => score >= 80);
console.log("Passing scores:", passingScores); // [85, 92, 88, 95]

// Filtering objects
const students = [
  { name: "Alice", grade: "A" },
  { name: "Bob", grade: "B" },
  { name: "Charlie", grade: "C" },
  { name: "David", grade: "A" }
];

const honorStudents = students.filter(student => student.grade === "A");
console.log("Honor students:", honorStudents);
// [{ name: "Alice", grade: "A" }, { name: "David", grade: "A" }]

// Removing falsy values
const mixedValues = [0, "hello", false, null, "world", undefined, "", 42];
const truthyValues = mixedValues.filter(Boolean);
console.log("Truthy values:", truthyValues); // ["hello", "world", 42]

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.