Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,939 questions

51,876 answers

573 users

How to rearrange an array and set arr[arr[index]] to index in TypeScript

1 Answer

0 votes
function rearrange_array(arr : any) {
    let tmp = [];
  
    for (let i = 0; i < arr.length; i++) {
        tmp[arr[i]] = i;
    }
  
    for (let i = 0; i < arr.length; i++) {
        arr[i] = tmp[i];
    }
}
  

const arr:number[] = [ 3, 1, 0, 4, 5, 2 ];
     
// arr[arr[0]] = 3 -> arr[3] = 0
// arr[arr[1]] = 1 -> arr[1] = 1
// arr[arr[2]] = 0 -> arr[0] = 2
// arr[arr[3]] = 4 -> arr[4] = 3
// arr[arr[4]] = 5 -> arr[5] = 4
// arr[arr[5]] = 2 -> arr[2] = 5
     
 rearrange_array(arr);
  
 console.log(arr);
 
 
 
 
/*
run:
 
[2, 1, 5, 0, 3, 4] 
 
*/


 
 

 



answered Aug 16, 2022 by avibootz
edited Aug 16, 2022 by avibootz
...