JavaScript Array Methods
48 Questions
0 Views

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson

Questions and Answers

Which of the following statements accurately distinguishes the push() and pop() methods from the shift() and unshift() methods in JavaScript arrays?

  • `push()` and `shift()` add elements, while `pop()` and `unshift()` remove elements, regardless of position.
  • `push()` and `unshift()` add elements to the end, while `pop()` and `shift()` remove elements from the beginning.
  • `push()` and `pop()` add/remove elements from the end of the array, while `shift()` and `unshift()` add/remove elements from the beginning. (correct)
  • `push()` and `pop()` add/remove elements from the beginning of the array, while `shift()` and `unshift()` add/remove elements from the end.

What is the purpose of the numb parameter in the splice() method, and how does its value affect the array?

  • It specifies the index at which to start inserting new elements. If it's 0, no elements are added.
  • It indicates the total number of elements that should remain in the array after the `splice()` operation. Elements are either added or removed to achieve this count.
  • It determines the number of elements to remove starting from the position defined by `pos`. A value of 0 means no elements are removed. (correct)
  • It sets a limit on the number of `itemX` parameters that can be inserted into the array. Excess parameters are ignored.

In the context of the splice() method, what occurs when the itemX parameters are provided after pos and numb?

  • The `itemX` parameters are appended to the end of the array, after the splice operation is complete.
  • The `itemX` parameters are inserted into the array at the position specified by `pos`. Existing elements at `pos` and beyond shift to the right to accommodate the new elements. (correct)
  • The `itemX` parameters replace the elements being removed, one-to-one, based on their order.
  • The `itemX` parameters are ignored because they are only relevant when removing elements from the array.

Which array methods modify the original array?

<p><code>push()</code> (B)</p> Signup and view all the answers

Given an array myArray = [10, 20, 30, 40, 50], what will myArray be after calling myArray.splice(2, 1, 35)?

<p>[10, 20, 35, 40, 50] (C)</p> Signup and view all the answers

When searching an array using indexOf(), what is a limitation compared to findIndex()?

<p>It cannot focus on properties of the string elements. (B)</p> Signup and view all the answers

If arr = [1, 2, 3, 4, 5], what does arr.slice(1, 4) return?

<p>[2, 3, 4] (A)</p> Signup and view all the answers

Which of these methods adds an element to the beginning of an array?

<p><code>unshift()</code> (B)</p> Signup and view all the answers

You have an array of Book objects and need to find the first book written by a specific author. Which method is most suitable?

<p><code>findIndex()</code> (C)</p> Signup and view all the answers

What is the primary purpose of the filter() method?

<p>To return all elements that satisfy a condition defined by a callback function. (D)</p> Signup and view all the answers

What is the primary difference between the slice() method and the splice() method on Javascript arrays?

<p><code>slice()</code> creates a new array based on a portion of an existing array; <code>splice()</code> modifies the content of an existing array. (A)</p> Signup and view all the answers

How does the return value of filter() differ from findIndex()?

<p><code>filter()</code> returns an array of all matching elements, while <code>findIndex()</code> returns the index of the first matching element. (A)</p> Signup and view all the answers

What does the map() method do to each element of an array?

<p>It transforms each element into a new element based on a provided function. (C)</p> Signup and view all the answers

What is the return value of the map() method?

<p>A new array with each element being the result of the callback function. (D)</p> Signup and view all the answers

Consider an array of Student objects. How could you use the map() method to create an array containing only the first names of the students?

<p>By providing a callback function that returns the <code>firstName</code> property of each <code>Student</code> object. (D)</p> Signup and view all the answers

Given an array of Game objects, how would you use map() to create a simplified array of strings representing the outcome of each game ('win', 'loss', 'tie', or 'not yet')?

<p>Apply <code>map()</code> with a callback function that checks the game's outcome and returns the corresponding string. (C)</p> Signup and view all the answers

What is the primary function of the slice() method when applied to an array?

<p>To return a new array containing a portion of the original array. (C)</p> Signup and view all the answers

How does the slice() method handle the element at the end position?

<p>It excludes the element at the <code>end</code> position from the new sub-array. (D)</p> Signup and view all the answers

What does the item parameter represent in the indexOf(), lastIndexOf(), and includes() methods?

<p>The specific value to search for within the array. (B)</p> Signup and view all the answers

If the item is not found within the array, what do the indexOf() and lastIndexOf() methods return?

<p>-1 (D)</p> Signup and view all the answers

How does the optional startPos parameter in indexOf(), lastIndexOf(), and includes() methods affect the search?

<p>It sets the index from which the search begins. (D)</p> Signup and view all the answers

What is a key distinction between using a loop with indexOf() and using the filter() method for finding multiple matches in an array?

<p><code>indexOf()</code> only returns the index of the first match, requiring a loop to find subsequent matches, whereas <code>filter()</code> returns all matches in a new array. (B)</p> Signup and view all the answers

In the context of JavaScript, what is a callback function?

<p>A function that is passed as an argument to another function, to be executed at a later point. (A)</p> Signup and view all the answers

Why are callback functions useful in designing flexible and modular code?

<p>They allow functions to be generalized, adapting behavior based on the specific callback provided. (D)</p> Signup and view all the answers

In the doSomethingMathy function, what is the purpose of the displayFunction parameter?

<p>To display the calculated value after the mathematical operations. (C)</p> Signup and view all the answers

Which of the following is a valid way to call the doSomethingMathy function, assuming useAnAlert, useHTML, and useTheConsole are defined as in the content?

<p><code>doSomethingMathy(50, useAnAlert)</code> (B)</p> Signup and view all the answers

What is the primary difference between indexOf() and findIndex() methods when searching an array?

<p><code>indexOf()</code> searches for a specific value, while <code>findIndex()</code> uses a callback function to define a search condition. (C)</p> Signup and view all the answers

Why might findIndex() be more suitable than indexOf() when searching for an object within an array of objects?

<p><code>indexOf()</code> only compares object references, while <code>findIndex()</code> can compare object properties. (D)</p> Signup and view all the answers

Consider an array of objects, each with 'name' and 'age' properties. Which of the following findIndex() calls correctly finds the index of the first object with an age greater than 25?

<p><code>array.findIndex(item =&gt; item.age &gt; 25)</code> (C)</p> Signup and view all the answers

What is the primary purpose of findLastIndex()?

<p>To find the index of the last element that satisfies a condition defined by a callback function. (C)</p> Signup and view all the answers

Given an array myArray = [{name: 'Alice', id: 1}, {name: 'Bob', id: 2}, {name: 'Alice', id: 3}], which method would be most efficient to find the index of the last object with the name 'Alice'?

<p><code>myArray.findLastIndex(obj =&gt; obj.name === 'Alice')</code> (B)</p> Signup and view all the answers

In what scenario would using find() be more appropriate than using findIndex()?

<p>When you only need to retrieve the first element that matches a condition, not its index. (D)</p> Signup and view all the answers

Given an array of objects, what is the expected outcome if the sort() method is called without a callback function and the objects lack a custom toString() method?

<p>The array will be sorted based on the default <code>toString()</code> representation, resulting in a consistent but likely unsorted order. (D)</p> Signup and view all the answers

What is the consequence of sorting an array of strings using the sort() method without a callback function, considering the default alphabetical sorting?

<p>Strings will be sorted alphabetically, but uppercase letters will precede lowercase letters. (A)</p> Signup and view all the answers

In the context of the sort() method, what do the two parameters passed to the callback function represent?

<p>Two elements from the array being compared to determine their relative order. (D)</p> Signup and view all the answers

How does the sort() method utilize the callback function to determine the order of elements within an array?

<p>The <code>sort()</code> method uses the callback function to compare pairs of elements, shuffling their positions until the array is fully sorted. (A)</p> Signup and view all the answers

Which of the following code snippets correctly uses the forEach() method to print only the even numbers from an array of integers?

<p><code>numbers.forEach(num =&gt; { if (num % 2 === 0) { console.log(num); } });</code> (A)</p> Signup and view all the answers

Given an array of mixed-case strings, how can you sort them alphabetically in a case-insensitive manner using the sort() method?

<p>Use <code>array.sort((a, b) =&gt; a.toLowerCase().localeCompare(b.toLowerCase()))</code>. (D)</p> Signup and view all the answers

What is the purpose of the map() method when transforming an array of one type (e.g., Blah) into an array of another type (e.g., Foo)?

<p>To apply a transformation function to each element, creating a new array with the transformed elements. (A)</p> Signup and view all the answers

Consider an array of objects with a numeric age property. How would you sort this array in descending order based on the age property?

<p><code>array.sort((a, b) =&gt; b.age - a.age)</code> (B)</p> Signup and view all the answers

What order does list.sort( (a, b) => b.price - a.price ) sort a list of products by price?

<p>Descending order (D)</p> Signup and view all the answers

Given let list1 = [3, -2, 5], what is the result of let list2 = list1.map( (a) => a*a )?

<p>[9, 4, 25] (A)</p> Signup and view all the answers

Given let list1 = [ "a", "happy", "nope", "whatever" ], what is the result of the following code?

let list2 = list1.map( (a) => { if( a.length < 5 ) return "short"; else return a; });

<p>[&quot;short&quot;, &quot;happy&quot;, &quot;short&quot;, &quot;whatever&quot;] (B)</p> Signup and view all the answers

What does the following code do?

let list1 = //some list of products on our website let list2 = list1.filter( (a) => a.price < 100 )

<p>Creates a new list (list2) containing only the elements from list1 where the price is less than 100. (C)</p> Signup and view all the answers

What data type will foo be after running the following code?

let list = //some list of products on our website...assume that they have a price property let foo = list.reduce( (acc, item) => { if(acc.price > item.price) return acc; else return item; });

<p>Product (D)</p> Signup and view all the answers

What does the optional second parameter in the reduce() method represent?

<p>The initial value of the accumulator (B)</p> Signup and view all the answers

What happens if you do not provide a starting value to the reduce() method?

<p>The accumulator starts with the first element of the list, and the item parameter starts with the second element. (C)</p> Signup and view all the answers

You have list of objects, each with a date property represented as a string 'YYYY-MM-DD'. How would you sort this list in chronological order (oldest to newest)?

<p><code>list.sort((a, b) =&gt; new Date(a.date) - new Date(b.date))</code> (A)</p> Signup and view all the answers

Flashcards

What does push() do?

Adds elements to the end of an array.

What does pop() do?

Removes and returns the last element of an array.

What does unshift() do?

Adds elements to the beginning of an array.

What does shift() do?

Removes and returns the first element of an array.

Signup and view all the flashcards

What does splice() do?

Adds/removes elements from an array, starting at 'pos'. 'numb' is how many to remove. 'itemX' are items to insert.

Signup and view all the flashcards

What is the 'start' parameter in slice()?

The starting index for extraction.

Signup and view all the flashcards

What is the 'end' parameter in slice()?

The ending index for extraction (exclusive).

Signup and view all the flashcards

What does slice() do?

Extracts a section of an array and returns a new array. It does NOT modify the original array.

Signup and view all the flashcards

Array slice() method

Returns a sub-array from start to end (exclusive) without modifying the original array.

Signup and view all the flashcards

indexOf/lastIndexOf/includes() - item parameter

An item in the array to search for.

Signup and view all the flashcards

indexOf/lastIndexOf/includes() - startPos parameter

Specifies the index to start searching from.

Signup and view all the flashcards

Callback function

A function passed as an argument to another function, to be executed at a later point.

Signup and view all the flashcards

Does slice() modify the original array?

Slice does NOT modify the original array.

Signup and view all the flashcards

indexOf/lastIndexOf/includes() return values

Returns a boolean or position of the item found.

Signup and view all the flashcards

Using startPos parameter

The search will begin at this index.

Signup and view all the flashcards

Callbacks: flexible design

Functions that accept callback functions create adaptable design patterns.

Signup and view all the flashcards

Display Function

A function that displays a value.

Signup and view all the flashcards

Passing Function Name

Passing the name of a function as an argument.

Signup and view all the flashcards

findIndex(), find(), findLastIndex()

Methods that search for a value based on a condition.

Signup and view all the flashcards

Callback Function (find)

A function that returns true when the desired element is found.

Signup and view all the flashcards

Flexibility of find()

They allow you to search based on properties other than equality.

Signup and view all the flashcards

Power of Callback Function

Check complex object properties, not simple equality.

Signup and view all the flashcards

Callback Function vs Value parameter

These methods use a callback function to determine if an element matches the search criteria, offering greater flexibility.

Signup and view all the flashcards

What does findIndex() do?

It returns the index of the first element that satisfies a provided testing function. Returns -1 if no element satisfies the function.

Signup and view all the flashcards

How is findIndex() more flexible than indexOf()

Unlike indexOf(), it uses a callback function to define the search condition, allowing for more complex searches based on properties of the elements.

Signup and view all the flashcards

What does the filter() method do?

It returns a new array containing all elements from the original array that satisfy a provided testing function.

Signup and view all the flashcards

Difference between index methods and filter()

indexOf(), lastIndexOf(), findIndex(), and findLastIndex() return the position of the first matching element or -1 if not found. filter() returns an array of all matching items.

Signup and view all the flashcards

What does the map() method do?

It transforms each element of an array into a new element, creating a new array with the transformed values.

Signup and view all the flashcards

What does the map() method return?

The map() method returns a new array with the same length as the original, but with each element transformed based on the provided callback function.

Signup and view all the flashcards

map() vs filter()

Use map() to modify each element in an existing array, creating a new array with the modified elements. Use filter() to select a subset of elements that meet specific criteria.

Signup and view all the flashcards

What does the lastIndexOf() and findLastIndex() method do?

It returns the position of the last element found and only the last position found (or -1 if not found)

Signup and view all the flashcards

What does map() do?

Transforms an array of one type into an array of another type using a provided function.

Signup and view all the flashcards

How does sort() work without a callback?

Sorts elements alphabetically (with uppercase before lowercase) if no callback is provided; otherwise, converts elements to strings and sorts.

Signup and view all the flashcards

What happens when sorting objects without toString()?

The sort() method calls toString() on objects to determine order when no callback is provided.

Signup and view all the flashcards

What does the sort() callback function receive?

Compares two elements to determine their order, returning a negative, positive, or zero value.

Signup and view all the flashcards

How does sort() use the callback result?

The callback determines the sorting order by returning a negative (a before b), positive (b before a), or zero value (equal).

Signup and view all the flashcards

What is the general purpose of forEach()?

Executes a provided function once for each array element in ascending index order.

Signup and view all the flashcards

How do I check if a number is even?

Use the modulo operator (%) to check if a number is even (num % 2 === 0).

Signup and view all the flashcards

How would you print only even numbers from a list of integers?

Use an if statement inside the forEach loop to only print even numbers.

Signup and view all the flashcards

list.sort( (a, b) => b.price - a.price )

Sorts products by price in descending order (highest to lowest).

Signup and view all the flashcards

list.sort( (a, b) => a.price - b.price )

Sorts products by price in ascending order (lowest to highest).

Signup and view all the flashcards

list.map( (a) => a*a )

Creates a new array with the results of calling a provided function on every element in the calling array. In this case squares all the numbers in list1.

Signup and view all the flashcards

list.map with conditional

Transforms strings in list1. Strings shorter than length 5 become 'short'; others stay the same.

Signup and view all the flashcards

list.filter( (a) => a.price < 100 )

Creates a new array with elements from list1 where the price is less than 100.

Signup and view all the flashcards

list.reduce to find highest price

Finds the product with the highest price in the list.

Signup and view all the flashcards

Optional parameter in reduce()

The starting value for the accumulator in a reduce() operation.

Signup and view all the flashcards

reduce() without initial value

If no starting value is provided to reduce(), the first element of the list is used as the initial accumulator value, and the second element is the first item.

Signup and view all the flashcards

Study Notes

  • In answering the array questions, indicate whether or not the method can modify the array.

Array Methods

  • The push() function adds items to the end of an array and requires a parameter to specify the item to add.
  • The pop() function removes and returns the last element of the array.
  • Both push() and pop() modify the array.
  • The shift() and unshift() methods deal with the front of the array, sliding elements over upon adding or removing elements.
  • Both shift() and unshift() modify the array.
  • The splice() function adds or removes elements from an array at a specified position.
  • It takes parameters such as pos to indicate the starting position, numb to specify the number of elements to remove, and itemX to specify the items to be inserted.
  • If numb is 0, nothing is removed.
  • The itemX parameters represent the items to be inserted at position pos, and elements at or after position pos are shifted to the right to accommodate new items.
  • splice() modifies the array.
  • The slice() method returns a sub-array and takes two generic parameters: start and end.
  • The sub-array starts at the start position and includes the element at that position, stopping at the end position but excluding the element at the end position.
  • slice() does not modify the original array.
  • The indexOf(), lastIndexOf(), and includes() methods search for elements in an array.
  • The generic parameters for these functions are item and startPos, where item specifies the item to search for.
  • These methods check if any element in the array is equal to item.
  • The includes() method returns a boolean.
  • indexOf() and lastIndexOf() return the position of the found item or -1 if not found.
  • By default, the search starts at position 0 (or the last position for lastIndexOf()).
  • startPos gives the ability to begin at a different position
  • indexOf(), lastIndexOf(), and includes() do not modify the array.

Callback Functions

  • A callback function is a function passed as a parameter to another function (the invoked function).
  • The invoked function uses the callback function as part of its operation, calling it at some point during execution.

Array Methods with Callback Functions

  • The findIndex(), findLastIndex(), and find() methods also use a callback function parameter; the callback function should return true for the element being searched.
  • indexOf(), lastIndexOf(), and includes() search for an exact element match, while find(), findIndex(), and findLastIndex() provide more flexibility by allowing you to check for specific properties using a callback function.
  • findIndex(), findLastIndex(), and find() do not modify the array.
  • The filter() method returns all elements that satisfy the callback function.
  • The "index" methods return the position of only one element, while filter() returns an array of elements, not a position.
  • filter() does not modify the array.
  • The map() method transforms each element of an array into something else resulting in a new output array with the transformed elements.
  • The forEach() method executes a provided function once for each array element.
  • map() does not modify the array.
  • The sort() method arranges the elements of an array in a specific order.
  • Without a callback function, it sorts alphabetically by default, treating uppercase letters as "less than" lowercase.
  • Objects are sorted by their string representation using toString().
  • A callback function for sort() takes two parameters, representing two elements of the array, and determines their order.

Reduce

  • The reduce() method condenses an array into a single value.
  • The optional parameter after the callback function for reduce() is the initial value of the accumulator
  • If no starting value is provided, the first element of the array is used as the initial accumulator value, and the second element is used as the current item.
  • If a starting value is provided, the accumulator is initialized with this value, and the first element of the array is used as the current item.

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Related Documents

Description

Explore the differences between push/pop and shift/unshift methods, the purpose of the numb parameter in the splice() method, and the behavior when itemX parameters are provided. Also, discover which array methods modify the original array and delve into searching arrays using indexOf() and findIndex().

More Like This

JavaScript Array Methods and Loops
3 questions

JavaScript Array Methods and Loops

EnterprisingAcademicArt avatar
EnterprisingAcademicArt
6. JavaScript Array
42 questions

6. JavaScript Array

MagnanimousCloisonnism avatar
MagnanimousCloisonnism
JavaScript Arrays and Methods
5 questions
Use Quizgecko on...
Browser
Browser