Reputation: 1
I'm trying to access a specific element in an array, but I'm only getting the first one. Any help with pointing out my error is appreciated.
let testArr = [[1, 2, 3],[4, 5, 6]];
const printArr = (someArr, i) => alert(someArr[i]);
printArr(testArr, [0][0]);
Expected Output
1
Actual Output
1, 2, 3
Upvotes: 0
Views: 390
Reputation: 2937
Or you could just do it without casting array like numbers or similar.
let testArr = [
[1, 2, 3],
[4, 5, 6],
];
const printArr = (someArr, arrNum, indNum) => someArr[arrNum][indNum];
printArr(testArr, 1, 0);
Upvotes: 0
Reputation: 11584
[0][0]
is actually 0
. This is the same as
a = [0];
a[0] === [0][0]; // 0
What you want to actually do is unclear. If you just want to pass a value, just pass that value, rather than the array and index separately.
printArr(testArr[0][0]);
If, for whatever reason, you need the index and array passed separately, then you can pass the indies as an array:
let testArr = [
[1, 2, 3],
[4, 5, 6],
[7, [8, 9], 10]
];
const printArr = (arr, indices) => console.log(indices.reduce((a, i) => a[i], arr));
printArr(testArr, [2, 1, 0]); // 8
Upvotes: 3
Reputation: 386680
You could take a function for getting a special value.
let testArr = [[1, 2, 3],[4, 5, 6]];
const printArr = (someArr, fn) => console.log(fn(someArr));
printArr(testArr, array => array[0][0]);
Upvotes: 0
Reputation: 943996
printArr(testArr, [0][0]);
aproximates to:
const some_array = [0];
const second_arg = some_array[0]
printArr(testArr, second_arg);
You are passing 0
as the second argument.
You can't pass arbitrary bits of JS syntax around.
Use two arguments instead.
let testArr = [[1, 2, 3],[4, 5, 6]];
const printArr = (someArr, i, j) => alert(someArr[i][j]);
printArr(testArr, 0, 0);
Upvotes: 1