Creating a fresh array by selecting specific elements at a desired index from an array of arrays

Consider the following scenario in JavaScript:

data = [[5,3,2],[2,7,4],[4,6,3],[2,6,4]]

An idea is to create a function that can take an array and an index as inputs, and then return a new array consisting of only the values at that specific index from each sub-array.

For instance:

result = customFunction(data, 1);

//expected outcome: result = [3,7,6,6]

Is there an efficient and effective way to achieve this objective?

Answer №1

Give this a shot:

Here's a helpful function to filter out indexes from a two-dimensional array: 

function filterIndexes(2dArray, index) {
    return 2dArray.map(function(subarray) {
         return subarray[index];
    });
}

Answer №2

let numbers = [
  [7, 2, 9],
  [1, 5, 8],
  [3, 6, 4],
  [2, 4, 5]
]

const extractColumn = function(arr, index) {
  return arr.map(element => element[index]);
}

const extractedResult = extractColumn(numbers, 1)

console.log(extractedResult)

Answer №3

It's important to remember that arrays are zero-based in your example. Therefore, for index 2, the correct answer is [2, 4, 3, 4]

The function can be written as follows:

const foo = [[5,3,2],[2,7,4],[4,6,3],[2,6,4]];

function bar(arr, index) {
    return arr.map( subarray => subarray[index] );
}

console.log( bar( foo, 2 ) );

A shorter alternative version would be:

const foo = [[5,3,2],[2,7,4],[4,6,3],[2,6,4]];
const bar = (arr, index) => arr.map( subarray => subarray[index] );

console.log( bar ( foo, 2 ) );

Answer №4

A potential solution could involve looping through the array and creating a new one:

foo = [[5,3,2],[2,7,4],[4,6,3],[2,6,4]]
function bar(arr, idx) {
   var selectedArr = [];
   arr.forEach(function(subArr) {
     selectedArr.push(subArr[idx]);
   });
   return selectedArr;
}


document.getElementById("result").innerText = bar(foo,2);
<span id="result"></span>

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

The error "Cannot set property '0' of undefined" typically occurs when trying to assign a value to an

Within the code snippet below, my goal is to iterate through the contents of an array: features[0]["values_"]["geometry"]["flatCoordinates"] When running the application, all console statements outside the for-loop successfully display data. However, upon ...

Struggling to display the array after adding a new item with the push method

Seeking assistance in JavaScript as a newcomer. I have written some code to print an array once a new item is added, but unfortunately, it's not displaying the array. I am puzzled as there are no errors showing up in the console either. In my code, I ...

Making an Ajax call using slash-separated parameters

Handling APIs that require slash-separated parameters in the URL can be quite tricky. Take for example: http://example.com/api/get_nearest_places/:en_type_id/:longitude/:latitude One way to build this URL is by concatenating strings like so: var longitu ...

What is the best way to transform the incoming data using JavaScript?

The data I have from Algolia in my project includes a seconds data presented as an array. This is the method I use to extract the seconds data from Algolia: @if(isset($content['length'])) <div class="flex items-center space-x-6"> ...

Display JSON information in a table using AngularJS

As I delve back into an old project, I've encountered a hurdle. My goal is to display some data in a table, but I seem to have forgotten the intricacies of working with JSON objects and Angular. The API response I'm receiving looks something lik ...

Expanding the use of tagged template literals for passing additional arguments

Currently, I am utilizing styled-components and creating components through their tagged template literal syntax like this: const Button = styled.button` background-color: papayawhip; border-radius: 3px; color: palevioletred; ` In a specific scenar ...

Combining nested arrays, objects, and properties into one comprehensive flat table through a left join

Overview I am utilizing the Microsoft OData Query Builder library to generate nested tables, but I require a flat table. To accomplish this, I have two potential solutions: Adjust the nested JSON data I receive to create a flat table. Allow the OData Qu ...

Is the onclick Syntax for async arrow function limited to working only with Ids?

I have a question about my code. I am curious as to why document.getElementById("myName").onclick functions correctly, while document.getElementByClassName("myClass").onclick does not work in the following example using an onclick arrow function. Does the ...

Encountering an error: Unable to access property 'main' as it is undefined in MUI v5

I encountered an issue while trying to implement page pagination for my Table following a tutorial. The error message I see in my browser is: Uncaught TypeError: Cannot read property 'main' of undefined at ButtonRoot.ownerState.ownerState ...

Tips for concealing a div upon reaching a specific scroll point, even with varying content sizes

Hey there! I am completely new to web programming and currently working on a landing page. The challenge I'm facing is that the content in the first column is dynamic, meaning it can vary in length. I'm looking for a way to hide my call-to-actio ...

Transferring Information Across Javascript Documents

I am facing a dilemma with using JSON data generated by one script in another script. I am unsure where to begin and have considered saving the JSON string to a text file for the second script to use, but this feels like a workaround rather than a proper s ...

In what part of my code should I integrate the .sort() method?

I am working on rendering a list of items in alphabetical order to the browser. I have previous experience using .sort() in other scenarios, but I am unsure about where to place it in this particular situation. In my current code, I initially placed the . ...

I'm encountering an issue with ESlint in my Vue.js project that I just can't seem to resolve

A couple of months back, I encountered this issue within my vue.js project. The error seems to be originating from lines 22, 23, and 24, which correspond to lines 45, 46, and 47 in the code block below. { "resource": "/C:/Users/Demo User ...

Error encountered: Application module "MyApp" not found

I have set up AngularJs and jQuery using RequireJs within a nodeJs framework. This is my main.js setup require.config({ paths: { angular: 'vendor/angular.min', bootstrap: 'vendor/twitter/bootstrap', jqu ...

Cancel all uncompleted axios requests and start fresh

I am currently utilizing the axios library for handling API requests. I find myself in a situation where I need to cancel all ongoing or pending requests and initiate new ones using a different API. I have attempted the following code: async getOldRespon ...

JavaScript: Pop-up form fades in from the top

I have successfully built a Modal form using only Javascript and Css. The animation effects in Bootstrap's modal, such as the card appearing FadeInDown and fading out with FadeInUp, caught my attention. I would like to implement similar animations wit ...

Problem: Values are not being posted with AJAX when using $(form).serialize()

I'm encountering an issue with submitting a form using AJAX. I initially tried to pass the data using $("#myForm").serialize(), but for some reason, the receiving page doesn't receive the data. Take a look at my form: <form id="myForm"> ...

Is it possible to dynamically change the 'amount' on a PayPal button or iframe?

My task is to create a checkout page that exclusively uses PayPal for payment processing. The challenge I face is that the purchase amount is not fixed; users can input the desired amount for their purchase (e.g. buying a £100 gift code). PayPal typicall ...

Is there a promise specified in the render function of Express node.js?

I have successfully rendered my index.html page, but now I need to send additional data via sockets. To do this effectively, I require a promise for the rendering process. Currently, the code is running synchronously, causing the socket data to be overwrit ...

How can I show the total sum of input values in a React.js input box?

Is there a way to dynamically display the sum of values entered in front of my label that updates automatically? For example, you can refer to the image linked below for the desired output Output Image I have initialized the state but I'm struggling ...