skip to Main Content

I’ve seen many questions on this subject on Stack Overflow, however, they all seem to be returning a single object. (Not what I want)

I have an array below;

const locations = [
    {"city": "London", "district": "Brixton", "id": "Eue3uFjUHKi6wh73QZLX"},
    {"city": "Manchester", "district": "Bury", "id": "QZiiUBgzZaJt2HcahELT"},
    {"city": "London", "district": "Hackney", "id": "v2itdyO4IPXAMhIU8wce"}
]

I would like to map this array into sections based on the "city" key.

My expected output is;

 [
    {
       city: "London",
       data: [
          {
             city: "London",
             district: "Brixton",
             id: "Eue3uFjUHKi6wh73QZLX"
          },
          {
             city: "London",
             district: "Hackney",
             id: "v2itdyO4IPXAMhIU8wce"
          }
       ]
    },
    {
       city: "Manchester",
       data: [
          {
             city: "Manchester",
             district: "Bury",
             id: "QZiiUBgzZaJt2HcahELT"
          }
       ]
    }
 ]

I have tried the below;

const groupedLocations = locations.reduce((groups, item) => {
  const { city } = item;
  if (!groups[city]) {
    groups[city] = [];
  }
  groups[city].push(item);
  return groups;
}, {});

However, this returns an object not an array.

2

Answers


  1. Here’s a working code:

    const groupedLocations = locations.reduce((groups, item) => {
      const { city } = item;
      
      let relatedGroup = groups.find((group) => group.city === city);
      if (!relatedGroup) {
        relatedGroup = { city, data: [] };
        groups.push(relatedGroup);
      }
    
      relatedGroup.data.push(item);
      return groups;
    }, []);
    

    reduce returns the type of whatever is returned from its reducer function. In your case it was an object, and that’s why you got an object at the end.
    I started with an array and each step I looked in the array to find the related group and push the city into that group’s data list.

    Hope this helps, good luck!

    Login or Signup to reply.
  2. Here is the answer based on normal loops without using high order functions:

    const locations = [
      { city: "London", district: "Brixton", id: "Eue3uFjUHKi6wh73QZLX" },
      { city: "Manchester", district: "Bury", id: "QZiiUBgzZaJt2HcahELT" },
      { city: "London", district: "Hackney", id: "v2itdyO4IPXAMhIU8wce" },
    ];
    
    function ObjectCreatorHelper(arr, keyMatcher, firstIndex, secondIndex) {
      let newObj = {};
      newObj[keyMatcher] = arr[firstIndex][keyMatcher];
      newObj["data"] = [];
      if (secondIndex != null)
        newObj["data"].push(arr[firstIndex], arr[secondIndex]);
      else newObj["data"].push(arr[firstIndex]);
    
      return newObj;
    }
    
    function grouper(arr, keyMatcher) {
      // to make optimization because in runnig loop   the length of array should not be calculated
      let len = arr.length;
      let temp = [];
      let arrLenDecrementor = 0;
    
      for (let i = 0; i < len - arrLenDecrementor; i++) {
        let isFound = false;
        let key1 = arr[i];
        for (let j = i + 1; j < len - arrLenDecrementor; j++) {
          let key2 = arr[j];
    
          if (key1[keyMatcher] && key2[keyMatcher]) {
            if (key1[keyMatcher] == key2[keyMatcher]) {
              //
              let n = ObjectCreatorHelper(arr, keyMatcher, i, j);
              temp.push(n);
              isFound = true;
    
              //delete the matched array value no longer needed
              arr.splice(j, 1);
              // decrease the lengh of array to make loop run less
              arrLenDecrementor++;
              //
            }
          }
        }
        //if not found the duplicate key then
        if (!isFound) {
          let n = ObjectCreatorHelper(arr, keyMatcher, i, null);
          temp.push(n);
        }
      }
    
      return temp;
    }
    
    let result = grouper(locations, "city");
    
    console.log(result);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search