5

I am facing problem to change the index values of an array according to given index in javaScript. i have searched on StackOverflow and found some solution but those not working for me of are not for javaScript. The below input array and index is mentioned.

   Input:  arr[]   = [101, 102, 103];
   index[] = [1, 0, 2];
   Output: arr[]   = [102, 101, 103]
   index[] = [0,  1,  2] 

The founded answers are reorder array according to given index

php - sort an array according to second given array

Rearrange an array according to key

Sorting an Array according to the order of another Array

Any kind of hint/solution is highly appreciated.

1

3 Answers 3

28

What exactly does not work for you?

const arr = [101, 102, 103];
const index = [1, 0, 2];

const output = index.map(i => arr[i]);
console.log(output);

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

1 Comment

Beware of possible compatibility issues with some versions of browsers, mainly arrow functions caniuse.com/#feat=arrow-functions
2

you can loop and add into new array

var arr    = [101, 102, 103];
var index = [1, 0, 2];
var newArr =[];

for(var i=0;i<index.length ;i++){
   newArr[i]=arr[index[i]]
 }
  console.log(newArr);

1 Comment

Can you tell me how can I rearrange with an array of objects?1: 12, 2: 13, 3: 14, col: 1, named_range: "Coll.Par", row: 1 I want named_range, row ,col first and then 1,2 & 3
1

Hope this helps!

Below we use .map because it returns a new Array and iterates over indexes since we want to sort unordered using the indexes.

We use the current index from indexes to pick from unordered and return the value.

// ES5
var unordered = [101, 102, 103];
var indexes = [1, 0, 2];

var ordered = indexes.map(function(index) {
  return (unordered[index]);
});

console.log(ordered);

// ES6
const unordered = [101, 102, 103];
const indexes = [1, 0, 2];

console.log(
  indexes.map(index => (unordered[index]))
);

If you want to get the indexes of the ordered Array back, you can use the method below.

var ordered = indexes.reduce(function(accumulate, index, j) {
  accumulate['values'].push(unordered[index]);
  accumulate['indexes'].push(j);

  return accumulate;
}, { 'values': [], 'indexes': []});

console.log(ordered);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.