Skip to main content

5. 7 Summarizing with reduce

 Summarizing with reduce   Understanding Reduce Purpose of Reduce : reduce is a higher-order function used to compute a single value from an array. It's instrumental in operations like summing up numbers or finding an item in an array that meets a specific criterion (e.g., the script with the most characters). Operation : It works by repeatedly taking an element from the array and combining it with a current value until all elements have been processed. This process is akin to folding or reducing the array into a single value. 🎨: Think of reduce like making juice from oranges. You start with a bunch of oranges (the array), and then you squeeze them one by one into a jug (the single value). Your hands (the combining function) do the squeezing, and you might already have some juice in the jug to start with (the start value). 👩‍🎓: The Mechanics of reduce - The reduce function takes three arguments: the array to reduce, a combining function, and a starting value. The combin...

4.10 Further arrayology

 Further arrayology


 
 

 

👩‍🎓: Array Manipulation Methods:

  1. Adding/Removing Elements:

    • push: Adds an element to the end of an array.
    • pop: Removes the last element from an array.
    • unshift: Adds an element to the beginning of an array.
    • shift: Removes the first element from an array.
  2. Managing Tasks:

    • The provided code shows a simple task queue where remember adds tasks to the end, getTask retrieves tasks from the start, and rememberUrgently adds tasks to the front, reflecting their urgency.
  3. Searching:

    • indexOf: Finds the first occurrence of a specified element in an array and returns its index, or -1 if it's not found.
    • lastIndexOf: Similar to indexOf, but starts searching from the end of the array.
  4. Slicing:

    • slice: Returns a new array containing a portion of the original array, specified by a start and end index.
  5. Concatenating:

    • concat: Merges two or more arrays into one new array.

🎨: Using Array Methods Creatively:

  • These methods can be combined in creative ways. The remove function demonstrates this by using slice to create a new array excluding a specific index, effectively removing an element.

📚: Examples of Array Methods:

  • indexOf and lastIndexOf example shows how you can locate elements within an array.
  • The slice method is showcased with different variations, illustrating how to copy portions of arrays.
  • The concat method is used to combine arrays or add elements to an array, which is illustrated in the remove function example.

💡: Understanding slice and concat:

  • The slice method is non-destructive; it doesn't change the original array but instead returns a new one.
  • concat is also non-destructive, creating a new array without altering the original arrays.

🔬: Function for Removing Elements:

  • The remove function is a practical example of using array methods to manipulate data. It shows how you can use slice to get parts of an array before and after a given index and then concat to join these parts back together, excluding the element at the given index.

🔄: Conclusion:

  • These array methods are powerful tools for data manipulation in JavaScript. Understanding and combining them allows for efficient and expressive programming patterns.

⚙️: It's important to note that these methods mutate the array or create new arrays, which can be a significant consideration for managing application state or during debugging. 

 

Function Breakdown

function remove(array, index) {
  return array.slice(0, index)
    .concat(array.slice(index + 1));
}
  1. Function Definition:

    • function remove(array, index) { ... }
    • This defines a function named remove that takes two parameters: array (the array from which an element will be removed) and index (the position of the element to be removed).
  2. Using slice Method:

    • array.slice(0, index): The slice method is used here to create a new array containing elements from the start of array up to, but not including, the element at the index. If index is 2, this slice includes elements at positions 0 and 1.
    • array.slice(index + 1): This creates another new array that starts from the element just after index and goes to the end of array. If index is 2, this slice starts from position 3.
  3. Combining Arrays with concat:

    • .concat(array.slice(index + 1)): The concat method is used to join the two sliced arrays. It merges the first part (up to index) with the second part (after index), effectively omitting the element at index.
  4. Returning the New Array:

    • The function returns the new array created by concatenating the two slices, which excludes the element at the specified index.

console.log(remove(["a", "b", "c", "d", "e"], 2));
// → ["a", "b", "d", "e"] 
  • In this example, the function is called with an array ["a", "b", "c", "d", "e"] and an index 2.
  • The goal is to remove the element at index 2 (which is "c").
  • array.slice(0, 2) returns ["a", "b"], and array.slice(2 + 1) returns ["d", "e"].
  • These are concatenated to form ["a", "b", "d", "e"], which is the original array without the element "c".

Conclusion

The remove function is a handy way to create a new array with a specific element removed, without modifying the original array. It leverages the slice and concat methods to achieve this in a clean and efficient way.

 

Function Breakdown


let todoList = [];
function remember(task) {
  todoList.push(task);
}
function getTask() {
  return todoList.shift();
}
function rememberUrgently(task) {
  todoList.unshift(task);
}

The program you provided defines three functions:

  1. remember(task): Adds the given task to the end of the todoList array.

  2. getTask(): Removes the first item from the todoList array and returns it.

  3. rememberUrgently(task): Adds the given task to the beginning of the todoList array.

Here's a step-by-step explanation of how the program works:

  1. The remember(task) function takes a task as input and appends it to the end of the todoList array using the push() method. This means that the new task will be added to the list of tasks that need to be completed.

  2. The getTask() function removes the first item from the todoList array using the shift() method. This means that the first task in the queue will be removed and returned.

  3. The rememberUrgently(task) function adds the given task to the beginning of the todoList array using the unshift() method. This means that the new task will be placed at the front of the list of tasks, making it the next task to be completed.

Conclusion

The program manages a queue of tasks by using the push() and shift() methods to add and remove tasks at the end of the array, and the unshift() method to add tasks at the beginning of the array. The getTask() function retrieves tasks from the front of the queue.

 

Link to the chapter in the book Eloquent Javascript:

 

Comments