Home > Mobile >  React Native Sort Dictionary Based on Array
React Native Sort Dictionary Based on Array

Time:02-28

I have a "reference" array that contains

[“Push”,”Pull, “Leg”]

and an array of dicts that looks like

{
    "bodyPart": "upper arms",
    "target": "biceps",
    "broad_target": "biceps",
    "ppl": "pull"
  },

{
    "bodyPart": "chest",
    "target": "pectorals",
    "broad_target": "chest",
    "ppl": "push"
  },
 
 {
    "bodyPart": "lower legs",
    "target": "calves",
    "broad_target": "legs",
    "ppl": "legs"
  },

I want the array to be sorted based on the PPL attribute based on the reference array.

So since the reference array is push, pull, leg, the array of dicts should look like

{
    "bodyPart": "chest",
    "target": "pectorals",
    "broad_target": "chest",
    "ppl": "push"
  },
{
    "bodyPart": "upper arms",
    "target": "biceps",
    "broad_target": "biceps",
    "ppl": "pull"
  },
 
 {
    "bodyPart": "lower legs",
    "target": "calves",
    "broad_target": "legs",
    "ppl": "legs"
  },

CodePudding user response:

Use Javascript sort function based on the index of the ppl attribute on the reference array (you can get this index using function indexOf). Here it is as a cute one-liner:

// Reference array
const arrRef = ["Push", "Pull", "Leg"];

// Dictionary array (order "Push - Leg - Push")
const arrDicts = [
    { "ppl": "Push" },
    { "ppl": "Leg" },
    { "ppl": "Push" },
];

// Sorting (should be "Push - Push - Leg")
arrDicts.sort((a, b) => arrRef.indexOf(a.ppl) - arrRef.indexOf(b.ppl));

EDIT: Adding the old proposed solution (back up array)

const arrRef = ["Push", "Pull", "Leg"];

const arrDicts = [
    {
        "bodyPart": "upper arms",
        "target": "biceps",
        "broad_target": "biceps",
        "ppl": "Push"
    },

    {
        "bodyPart": "chest",
        "target": "pectorals",
        "broad_target": "chest",
        "ppl": "Pull"
    },

    {
        "bodyPart": "lower legs",
        "target": "calves",
        "broad_target": "legs",
        "ppl": "Leg"
    },
];

// Create a back up array and iterate on the reference array, filtering the actual dicitionary array with `ppl == current reference`
const backupArr = [];
for (const ref of arrRef) 
    backupArr.push(...arrDicts.filter(x => x.ppl == ref))

// Now backupArr is ordered as you want to
console.log(backupArr)

Please take in consideration this way of sorting the array will not include objects of the dictionary array that have a ppl attribute that is not in the reference array.

  • Related