0

enter image description here

If there is a cell configured like this, the desired result is

{samsung, [Galaxy S20, Galaxy S21, Galaxy S22, Galaxy S23]}, {apple, [iPhone 13]}, {lg,[g7, g8]}

In this way, I would like to obtain data in Java's HashMap<String, List<String>> format.

What should I do?

11
  • No direct way. Loop through to create Map Commented Oct 4, 2023 at 9:25
  • @TheMaster If so, does spreadsheet.getActiveRange().getValues() read horizontally in the specified range, do you know how to read horizontally? Commented Oct 4, 2023 at 14:30
  • Sheets api can read horizontally. But it's easy to transpose: stackoverflow.com/a/16705104 Commented Oct 4, 2023 at 14:34
  • @TheMaster Sorry... Oh, not horizontally, but vertically.. I read Samsung row, and then apple row.. This way Commented Oct 4, 2023 at 14:38
  • I got what you mean. The previous comment is correct and perfect. Sheets api can read both ways( use Advanced Google services). But the easy way is just to transpose. See previous link. Commented Oct 4, 2023 at 14:40

1 Answer 1

0

Try reduce:

/*<ignore>*/console.config({maximize:true,timeStamps:false,autoScroll:false});/*</ignore>*/ 
//getValues result
const d = [
  ['Samsung', 'Apple'],
  ['Galaxy S20', 'iPhone 13'],
  ['Galaxy S21', 'iPhone14'],
];

//Transpose example if needed 
const transposedArr = d[0].map((_, i) => d.map((r) => r[i]));
console.log(transposedArr);

const m = d.reduce((a, r) => {
  const o = Array.isArray(a) ? a.reduce((o, c) => ((o[c] = []), o), {}) : a;
  r.forEach((e, i) => o[d[0][i]].push(e));
  return o;
});
console.log(m);
<!-- https://meta.stackoverflow.com/a/375985/ -->    <script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.