2

I have an integer array

let arr=[7,1,5,3,6,4]

i am using this array to sort it in ascending order and extract the position of the first smallest element in the original array.My function is defined as

const maxProfit = function(prices) {
    let org=prices
    prices.sort((a,b)=>{return a-b})
    console.log(org)
    let ind=org.indexOf(prices[0])
    console.log(ind) 
};

console.log(maxProfit([7,1,5,3,6,4]))

i was interested in the value of org which is suppose to be [7,1,5,3,6,4] instead i got it as [1,3,4,5,6,7] why the assigning of the original array not working here?

3
  • 2
    This let org=prices doesn't clone the array. It's the same (now sorted) array. Commented Mar 9, 2023 at 6:21
  • let org = prices.slice(). Commented Mar 9, 2023 at 6:29
  • Related question. Commented Mar 9, 2023 at 14:21

1 Answer 1

3

Arrays are not primitive types and can't be cloned with = operator. For a relatively small array, you can just simply clone it like this

let arr = [1,2,3]
let newArr = arr.slice()

now you can perform whatever you want on newArr and it will not affect the original array

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

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.