Home > database >  entering values into an array in react from given 2d array
entering values into an array in react from given 2d array

Time:07-22

I want to enter the first value from every array inside a 2d array, I get the 2d array from the server and my intentions are to use it in one of the client pages (as chart data).

Here is the relevant code:

  React.useEffect(() => {
    fetch("http://localhost:3001/bitcoin")
      .then((res) => res.json()) 
      .then((data) => setData(data.message))
      .then((dates) => {
        //code right here
      })
  }, []);

Any idea how to implement it?

CodePudding user response:

It's too easy :

const twoDArray = [
    ["a", "b", "c"],
    ["A", "B", "C"],
    ["aa", "bb", "cc"],
    ["AA", "BB", "CC"] ]

const firstElements = twoDArray.map(item => item[0]);

console.log(firstElements);

// answer: [ 'a', 'A', 'aa', 'AA' ]

Let me know if it is what you exactly need

CodePudding user response:

first method : you can use for...of like this :

    const Arr  = [ 
    [ 1,2,3,4], 
    ['one',  'two' , 'three'], 
    ['un' ,'deux', 'trois' ], 
    
]

const ArrOfFirstValues = []
for(key of Arr){
   ArrOfFirstValues.push(key[0])
}

console.log(ArrOfFirstValues)

the output is : [ 1, 'one', 'un' ]

Second method :

you can use .map to iterate it :

const Arr  = [ 
    [ 1,2,3,4], 
    ['one',  'two' , 'three'], 
    ['un' ,'deux', 'trois' ], 
    
]
console.log(Arr )

const ArrOfFirstValues  =  Arr.map(arr => arr[0])

console.log(ArrOfFirstValues)

the output will be :

[ 1, 'one', 'un' ]
  • Related