Accessing array elements in JavaScript from two different scopes

I can't seem to grasp how specific array values are called and displayed:
I've included some questions inside the code. Please review and explain why the array displays one result within the function, but a different result outside of it. You can run the code on websites like repl.it

var passengers = [ ["Thomas", "Meeks"], 
                   ["Gregg", "Pollack"], 
                   ["Christine", "Wong"], 
                   ["Dan", "McGaw"] ];

var results = passengers.map(function (array) {
    // This section prints out only the first names--the entire first column. Why does this happen? 
    console.log(array[0]);
});

console.log(); // Adding empty space

// Why does this next line print only the first row of passengers as expected, while array[0] displayed all first column data?
console.log(passengers[0]);

Answer №1

When you use the map function with an array of arrays like this:

var results = passengers.map(function (array) {
    // This code snippet prints out the first names, which are in the first column of each inner array.
    console.log(array[0]);
});

The map function is looping through the outer array. Each element of the outer array, which is an inner array, gets passed as a parameter into the function. So when we call console.log(array[0]), it prints the first element of each inner array.

To simplify, the above code is similar to:

 console.log(passengers[0][0]);
 console.log(passengers[1][0]);
 console.log(passengers[2][0]);
 console.log(passengers[3][0]);

In this example, only the outer array (first index) is being iterated over. The inner array index remains at zero.

However, in the code snippet below:

console.log(passengers[0]);

It simply prints the entire first inner array, as it refers to the first element of the outer array.

For more information:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dealing with routing challenges in AngularJS and Symfony

I'm currently struggling to integrate Symfony2 and AngularJS together, encountering some challenges in the process: There are conflicts with the routing system Angular does not seem to recognize the Angular symbols within Twig templates. Here is th ...

Using Promise to manipulate objects and arrays returned from functions

https://i.stack.imgur.com/jvFzC.png router.get('/', function (req, res, next) { var size = req.params.size ? parseInt(req.params.size) : 20; var page = req.params.page ? req.params.page>0 ? (size&(parseInt(req.params.page)-1)) : ...

"An error appeared while using jQuery's mouseover function - unrecognized

Here is the code snippet I am working with: <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="portal" style="width:50px;height:50px;background:black" data-target="whatever"></div> < ...

Adjustable dimensions and the AngularJS framework

Upon page load, a directive is triggered to resize the content to fit within the correct dimensions. However, there seems to be an issue when a service call populates the model of a specific section of content after the resizing has taken place. The elemen ...

Ways to retrieve a specific element's reference from an XML-defined string-array on Android

In my XML file, I have a massive string array with around 250 elements. Here is an example: <string-array name="Descriptions"> <item>A good raiding strategy is to fill your Army Camp with Giants and Archers; together they can easily wipe o ...

The issue of elements flickering while being hidden and shown with jQuery has been observed in both Chrome and

Having trouble with a simple animation using jQuery? While it may work smoothly in Firefox, you might be experiencing flickering in Chrome and Edge. Check out this jsfiddle for reference: HTML <div id="boxes-wrapper"> <div class="box"></ ...

Modify the directive when the scope variable undergoes changes

Utilizing an http request, I am retrieving data from a json file that I then utilize in my controller. app.controller('mainCtrl', ['$scope', 'loaderService', function ($scope, loaderService) { //Getting data from the s ...

Tips on retrieving a value from an ajax callback function

One of the functions I have is called GetITStaffList function GetITStaffList(){ var go_path = "Server/ITComplains.php?action=GetITStaffList&vars=0"; $jqLibrary.get(go_path, {}, function(data) { var parseData = JSON ...

Guide on applying CSS to option tag within a select element in VUE.js

I am attempting to design a dropdown menu that resembles the one shown in the image. However, I'm currently unable to include any CSS styling. Can anyone provide guidance on how to create a customizable select dropdown in Vue? https://i.stack.imgur.c ...

Avoid the occurrence of $("html").ajaxError() by ensuring it is not present in any of the $.ajax

$("html").ajaxError(function (event, jqXHR, ajaxSettings, thrownError){ //display appropriate message depending on the error. }); Furthermore, I am transmitting JavaScript errors to the server via $.ajax() within the catch block and using the window.one ...

What is the best way to differentiate the handling of a 401 Unauthorized response from other errors within an Angular 8 service that utilizes RxJS?

My REST API implementation requires an access token for user identification with each call. If the token is missing or expired, the endpoint returns a 401 UNAUTHORIZED response. There are instances where I make API calls using a timer in my service class: ...

The Race of Speed and Stamina: A Modern Twist with Arrays and Pointers

My current assignment involves recreating the classic tale of the tortoise and the hare using C programming with pointers. So far, I have developed a code that generates 70 rows of arrays filled with zeros, where positions 2 and 3 represent the tortoise an ...

Guide to extracting a targeted value from a collection of JSON Objects in a NodeJS environment

I've been attempting to use the code below to extract the executionArn, but I'm encountering the following error Error [SyntaxError]: Unexpected token o in JSON at position 1 at JSON.parse (<anonymous>) Is there a way to retrieve the e ...

A dynamic search feature implemented with PHP, MySQL, and AJAX

I have implemented an ajax call to fetch data from my mysql database when searching for users. Below is the corresponding html code; <input type="text" id="partnerName" name="partnerName" class="form-control" placeholder="Type to search partners...."& ...

What is the reasoning behind an empty input value being considered as true?

I am facing an issue with the following code that is supposed to execute oninput if the input matches the answer. However, when dealing with a multiplication problem that equals 0, deleting the answer from the previous calculation (leaving the input empt ...

Converting an array of objects into a flat array of objects with Javascript

My data array requires conversion to a flattened array returning new header and data. For instance, the first object contains a name with three data points: "title, first, last." The desired output is: From : { gender: 'male', name: { ...

Utilizing an HTML time picker for scheduling specific time intervals

Is it possible to use an HTML time picker with a specific interval? https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/time According to the link, the step attribute is supported, but I have tested it on the latest versions of Chrome, Edge, ...

Utilizing the Route.post() method in Node.js

I'm currently developing a Node.js application and I'm facing an issue while trying to access functions from my index.js file in the calls.js controller. Every time I include var IndexBot = require('/root/afstudeerwerk/chatbotPIROS/index&ap ...

What is preventing Safari and Firefox from properly handling audio data from MediaElementSource?

It appears that neither Safari nor Firefox can process audio data from a MediaElementSource with the Web Audio API. var audioContext, audioProcess, audioSource, response = document.createElement('h3'), display = document.createElement( ...

PHP code snippet: Calculate the total sum of elements within an array

Here is an example of the array structure: array(2)( ['id'] => "59898441545", ['total'] => array( [0] => 2, [1] => 5 [2] => 10 [3] => 35 ) ); My goal is to transform the 'total' key from an array into the ...