Anwar
Anwar

Reputation: 4508

Combine 2 columns into 1 column by a group

I have an array of objects with two fields: Category and Name.

I call and an endpoint and I get something like this.

+----------+----------+
| Category | Name     |
+----------+----------+
| A        | product1 |
+----------+----------+
| A        | product2 |
+----------+----------+
| A        | product3 |
+----------+----------+
| B        | product4 |
+----------+----------+
| B        | product5 |
+----------+----------+
| C        | product6 |
+----------+----------+
| D        | product7 |
+----------+----------+
| D        | product8 |
+----------+----------+

But I need to transform this array into a single column so that a category comes first then the names under the same category come second.

Here is the result that I'm looking for.

+------------+
| One Column |
+------------+
| A          |
+------------+
| product1   |
+------------+
| product2   |
+------------+
| product3   |
+------------+
| B          |
+------------+
| product4   |
+------------+
| product5   |
+------------+
| C          |
+------------+
| product6   |
+------------+
| D          |
+------------+
| product7   |
+------------+
| product8   |
+------------+

Upvotes: 1

Views: 50

Answers (1)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48683

You can reduce the items with a helper variable that stores the last value.

let data = [
  { "Category": "A", "Name": "product1"	},
  { "Category": "A", "Name": "product2"	},
  { "Category": "A", "Name": "product3"	},
  { "Category": "B", "Name": "product4"	},
  { "Category": "B", "Name": "product5"	},
  { "Category": "C", "Name": "product6"	},
  { "Category": "D", "Name": "product7"	},
  { "Category": "D", "Name": "product8"	}
];

console.log(transform(data, 'Category', 'Name'));

function transform(data, categoryField, nameField) {
  let last = null; // Helper
  return data.reduce((result, item) => {
    if (last == null || last[categoryField] != item[categoryField]) {
      result.push(item[categoryField]);
    }
    result.push(item[nameField]);
    last = item; // Update
    return result;
  }, []);
}
.as-console-wrapper { top: 0; max-height: 100% !important; }

Upvotes: 1

Related Questions