0

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", ""]

4 Answers 4

2

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);

Sign up to request clarification or add additional context in comments.

2 Comments

@SreekanthReddy sure let me check
2

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))

1 Comment

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

1 Comment

1

With lodash you can just use the index as an iteratee:

const result = _.map(a, 1);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.