Get all 0 index data in 2d array javascript
let a = [["", "2", "", ""], ["1", "3", "", ""], ["", "", "4", ""]]
index = 0
output = ["", "1", ""]
Similarly get all remaining index data
index= 1
output = ["2", "3", ""]
You can use Array#map method with ES6 destructuring feature. Destructuring helps to extract certain property from an object(Javascript Array is also an object).
let a = [
["", "2", "", ""],
["1", "3", "", ""],
["", "", "4", ""]
];
let index = 0;
let output = a.map(({[ index ]: v }) => v)
console.log(output);
index = 1;
output = a.map(({[ index ]: v }) => v)
console.log(output);
You can use reduce
Loop through arr and for each element in arr loop through to get the desired index value and push it to op.
let a = [["", "2", "", ""], ["1", "3", "", ""], ["", "", "4", ""]]
function getIndex(arr,index){
return arr.reduce((op,inp) => {
let val = inp.find((e,i) => i === index )
op.push(val)
return op
},[])
}
console.log(getIndex(a,0))
console.log(getIndex(a,1))
To get the first index:
const result = Array.map(a=>a[0]);
result will contain the first index of all the elements in the nested array. This works by iterating through the array and fetching the first index elements