0

This might be stupid question however, I failed an interview because of this so asking. Does any one know how to clone an array of numbers into state. I have seen examples of objects. I have tried spread operator no luck, tried JSON.parse no luck.

const [Sorted,setSorted]=useState([])
let a=[1,3,5]
let b=[2,4,6]
function sorts(){
      let c=[...a,...b];
      return(c.sort());//it will return[1,2,3,4,5,6]
}
useEffect(()=>{
    let sortedArr=sorts();
    setSorted([...sortedArr]);//No use
    setSorted(JSON.parse(JSON.stringify(sortedArr));//No use
},[])


//Printing using Map

Please ignore any typing mistakes. Thank you

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Sumant GK
  • 300
  • 2
  • 8
  • 2
    lacking more information... the only thing I can say is that it's weird to use `let`... could also be done in a one liner: `setSorted([...a, ...b].sort())` – Noriller Aug 17 '21 at 17:25
  • `[8, 1, 78].sort()` would result to `[1, 78, 8]`. See [How to sort an array of integers correctly](https://stackoverflow.com/q/1063007/1218980) – Emile Bergeron Aug 17 '21 at 17:59

2 Answers2

1

I've tried to replicate the error in a codesandbox, the only thing causing an error, was a missing paranthesis. However your code was really hacky and unnecessary long. This is cleaner and works: https://codesandbox.io/s/flamboyant-pasteur-c9c83?file=/src/App.js

Jonas Hendel
  • 578
  • 4
  • 17
  • Please include the relevant information into the answer itself. Off-site references and resources are ok, as long as the answer is still clear without them. – Emile Bergeron Aug 17 '21 at 17:56
0

By simplifying your code a little bit (mostly just removing the sorts function from the body of your code and cleaning up the useEffect hook), I was able to get it to work

import { useState, useEffect } from "react";

function sorts(firstArr, secondArr) {
  let c = [...firstArr, ...secondArr];
  return c.sort();
}

export default function App() {
  const [Sorted, setSorted] = useState([]);
  const a = [1, 3, 5];
  const b = [2, 4, 6];
  
useEffect(() => {
    let sortedArr = sorts(a, b);
    setSorted([...sortedArr]);
  }, []);

  return (
    <div className="App">
      <h2>Sorted Array Below</h2>
      <p>{JSON.stringify(Sorted)}</p>
    </div>
  );
}
zac5482
  • 99
  • 10