Matriz dada:
var someAnswers = [ { answer: 'Lyndon Johnson', // answer A comment: '...' }, { answer: 'Richard Nixon', // answer B comment: '...' }, { answer: 'Jimmy Carter', // answer C comment: '...' }, { answer: 'Gerald Ford', // answer D comment: '...' } ];Algunos pedidos personalizados:
customOrder = 'A, C, B, D';o
customOrder = ['A', 'C', 'B', 'D'];Haz algo como esto:
someAnswers.sort(customOrder);Resultado deseado:
[ { "answer": "Lyndon Johnson", "comment": "..." }, { "answer": "Jimmy Carter", "comment": "..." }, { "answer": "Richard Nixon", "comment": "..." }, { "answer": "Gerald Ford", "comment": "..." } ]Otro pedido personalizado:
anotherCustomOrder = 'D, B, A, C';o
anotherCustomOrder = ['D', 'B', 'A', 'C'];Haz algo como esto:
someAnswers.sort(anotherCustomOrder);Resultado deseado:
[ { "answer": "Gerald Ford", "comment": "..." }, { "answer": "Richard Nixon", "comment": "..." }, { "answer": "Lyndon Johnson", "comment": "..." }, { "answer": "Jimmy Carter", "comment": "..." } ]Si estuviera dispuesto a reemplazar las letras con números en customOrder, podría hacer algo como esto:
customOrder = [0, 2, 1, 3]; sort(someAnswers, customOrder) { res = []; customOrder.forEach((n) => { res.push(someAnswers[n]); } return res; }Alternativamente, si realmente quieres usar letras:
customOrder = ["A", "C", "B", "D"]; sort(someAnswers, customOrder) { res = []; customOrder.forEach((n) => { res.push(someAnswers[n.charCodeAt(0) - 65]); } return res; }Puede crear un objeto con los índices según el orden deseado y luego usar la función Array.prototype.map y extraer los valores usando la matriz de índices creada anteriormente.
const someAnswers = [ { answer: 'Lyndon Johnson', comment: '...' }, { answer: 'Richard Nixon', comment: '...' }, { answer: 'Jimmy Carter', comment: '...' }, { answer: 'Gerald Ford', comment: '...' }], answerIndexes = ['A', 'B', 'C', 'D'].reduce((a, c, i) => ({...a, [c]: i}), {}), customOrder = ['A', 'C', 'B', 'D'], sorted = customOrder.map(L => someAnswers[answerIndexes[L]]); console.log(sorted); .as-console-wrapper { max-height: 100% !important; top: 0; } const sorting = (currentArray, indexArr) => { const reArrangedArr = []; const deepCopied = JSON.parse(JSON.stringify(currentArray)); indexArr.forEach(index => reArrangedArr.push(deepCopied[index])); return reArrangedArr; } var someAnswers = [ { answer: 'Lyndon Johnson', // answer A comment: '...' }, { answer: 'Richard Nixon', // answer B comment: '...' }, { answer: 'Jimmy Carter', // answer C comment: '...' }, { answer: 'Gerald Ford', // answer D comment: '...' } ]; console.log(sorting(someAnswers, [3,0,1,2]))