The entries() method of Array in JavaScript returns a new iterator object that contains the key/value pairs for each index in the array. The key is the index number and the value is the element at that index. This method does not change the original array.
- entries() returns an iterator, not an array directly.
- It's useful for accessing both indices and values for array operations.
- It works on any iterable object, not just arrays.
// Declare and initialize an array of trains const trains = ["Bullet", "Metro", "Express", "Freight"]; // Get the iterator object from the entries() method const trainEntries = trains.entries(); // Iterate over the key/value pairs using a for...of loop for (const [index, train] of trainEntries) { // Log the index and the train to the console console.log(index, train); } // Output: // 0 Bullet // 1 Metro // 2 Express // 3 Freight
Explanation:
- trains.entries() creates an iterator with key-value pairs for each train.
- The for...of loop iterates through the pairs, accessing index and train names.
const aeroplanes = ["Boeing 747", "Airbus A380", "Concorde"]; const planeEntries = aeroplanes.entries(); console.log(planeEntries); // Output: [[0, "Boeing 747"], [1, "Airbus A380"], [2, "Concorde"]] //Array.from(): This method converts an iterable object into a new array const planeArray = Array.from(planeEntries); planeArray.forEach(([index, plane]) => { console.log(`Aeroplane at index ${index}: ${plane}`); }); // Output: // Aeroplane at index 0: Boeing 747 // Aeroplane at index 1: Airbus A380 // Aeroplane at index 2: Concorde
Explanation:
- aeroplanes.entries() creates an iterator for aeroplanes.
- The forEach() method iterates and logs index-plane pairs.
Please note :
The forEach method does not work directly on the output of entries() because entries() returns an iterator, not an array. Iterators are objects that allow you to traverse elements one at a time, but they don't have methods like forEach that are specific to arrays.
Array.from(): This method converts an iterable object into a new array. Once you have an array, you can use array methods like forEach.
const buses = ["Double-Decker", "School Bus", "Minibus"]; const busEntries = buses.entries(); console.log(busEntries.next().value); // Output: [0, "Double-Decker"] console.log(busEntries.next().value); // Output: [1, "School Bus"] for (const [index, bus] of busEntries) { console.log(`Bus at index ${index}: ${bus}`); } // Output: // Bus at index 2: Minibus
Explanation:
- buses.entries() creates a bus iterator.
- next() method accesses individual entries, starting from the first.
- The for...of loop iterates from the third entry due to previous next() calls.