Home > front end >  restructure position of array elements
restructure position of array elements

Time:07-04

I have an array called myArray with objects as elements. What I'm trying to achieve is to restructure the position of the array elements without having two objects with the same key next to each other. The method I'm using right now starts to work but messes up after going halfway. How can I achieve this? Thanks in advance.

what I'm trying to achieve: finalArray = [{ "morning": "..." }, { "evening": "..." }, { "morning": "..." }, { "evening": "..." }, { "morning": "..." }, { "evening": "..." }, { "morning": "..." }, { "evening": "..." }, { "evening": "..." }, { "evening": "..." }]

const myArray = [{
  "morning": "23_6557"
}, {
  "evening": "7665_908"
}, {
  "evening": "545_787"
}, {
  "evening": "8774_957"
}, {
  "morning": "434_6447"
}, {
  "morning": "775_67"
}, {
  "evening": "4554_8774"
}, {
  "evening": "224_74"
}, {
  "evening": "43_112"
}, {
  "morning": "32_47"
}]

orderedArray = []
unOrderedArray = []

myArray.forEach((obj) => {
  //if the orderedArray is empty push a random array to it
  if (orderedArray.length == 0) {
    orderedArray.push(obj)
  }

  Object.keys(obj).forEach((key) => {
    //get the last element in the orderedArray and check if its key is equal to the new obj key
    if (Object.keys(orderedArray.at(-1))[0] != key) {
      //get a random object from myArray with key not equal to last orderedArray object key and push it to orderedArray
      orderedArray.push(obj)
    } else {
      //get a random object from myArray with key equal to last orderedArray object key and push it to unOrderedArray
      unOrderedArray.push(obj)
    }
  });
});

const finalArray = orderedArray.concat(unOrderedArray)
console.log(finalArray)

CodePudding user response:

One way is to first group the data by property, and then alternate between the groups to extract an element:

const myArray = [{"morning": "23_6557"}, {"evening": "7665_908"}, {"evening": "545_787"}, {"evening": "8774_957"}, {"morning": "434_6447"}, {"morning": "775_67"}, {"evening": "4554_8774"}, {"evening": "224_74"}, {"evening": "43_112"}, {"morning": "32_47"}];

// Create a map keyed by the properties
const map = new Map(myArray.map(o => [Object.keys(o)[0], []]));
// Populate the arrays that are associated by those properties
for (const o of myArray) map.get(Object.keys(o)[0]).push(o);
// Extract the arrays from this map
const groups = [...map.values()];

// Alternate between the groups to pull objects from them
const result = [];
while (groups.length) {
    const group = groups.shift();
    result.push(group.shift());
    if (group.length) groups.push(group);
}
console.log(result);

  • Related