0

I want to sort the data in the array according to user input. Follow the example below. What do I have to do?

array data sample

0: Array
   0: "1"
   1: "text1"
   2: "text2"
   3: "text3"
1: Array
   0: "2"
   1: "text1"
   2: "text2"
   3: "text3"
2: Array
   0: "3"
   1: "text1"
   2: "text2"
   3: "text3"

text input: 3, 1, 2

result

0: Array
   0: "3"
   1: "text1"
   2: "text2"
   3: "text3"
1: Array
   0: "1"
   1: "text1"
   2: "text2"
   3: "text3"
2: Array
   0: "2"
   1: "text1"
   2: "text2"
   3: "text3"
2
  • What did you try so far? Please share your code. Also Your sample Data and result doesn't look line array at all. Commented Aug 3, 2018 at 9:01
  • You want to map the user input to the index of inner arrays or to the values at oth position of each inner array? Commented Aug 3, 2018 at 9:10

2 Answers 2

2

    let yourObj = {0:{ 
       0: "1",
       1: "text1",
       2: "text2",
       3: "text3"},
    1: {
       0: "2",
       1: "text1",
       2: "text2",
       3: "text3"},
    2: {
       0: "3",
       1: "text1",
       2: "text2",
       3: "text3"}
    },
    input = [3,2,1];

    let sortArr = (input) => {
    
    let obj = {};
    
    for(let i = 0; i< input.length; i++){
    obj[i] = yourObj[--input[i]];
    
    }
    return obj;
    }

     console.log(sortArr(input))   //Call sort array here

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

Comments

1

let arr = [ ["1","text1","text2","text3"],["2","text1","text2","text3"],["3","text1","text2","text3"]]
const newOrder = [3,2,1];

let result = newOrder.map(idx => arr.find(el => el[0] == idx))

console.log(result)

2 Comments

I'm sorry. I tried the code and it works. But Jquery in project is not use "=>" How do I fix it?
let result = newOrder.map(function(idx){return arr.find(function(el){return el[0] == idx})})

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.