From f2bbcdd10ad4e91f6194737d48e6e0ccb2ce7d73 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 4 Jun 2023 00:03:48 +0200 Subject: [PATCH] =?UTF-8?q?problems(js):=20add=20=E2=80=9C2675.=20Array=20?= =?UTF-8?q?of=20Objects=20to=20Matrix=E2=80=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- problems/js/array-of-objects-to-matrix.js | 49 +++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 problems/js/array-of-objects-to-matrix.js diff --git a/problems/js/array-of-objects-to-matrix.js b/problems/js/array-of-objects-to-matrix.js new file mode 100644 index 0000000..f73f1e6 --- /dev/null +++ b/problems/js/array-of-objects-to-matrix.js @@ -0,0 +1,49 @@ +const isObject = x => x !== null && typeof x === 'object'; + +const getKeys = object => { + if (!isObject(object)) { + return ['']; + } + + let result = []; + + Object.keys(object).forEach(key => { + getKeys(object[key]).forEach(subKey => { + result.push(subKey ? `${key}.${subKey}` : key); + }); + }); + + return result; +}; + +const getValue = (obj, path) => { + let [value, i, paths] = [obj, 0, path.split('.')]; + for (i = 0; i < paths.length && isObject(value); ++i) { + value = value[paths[i]]; + } + + if (i < paths.length || value === undefined || isObject(value)) { + return ''; + } + + return value; +}; + +/** + * @param {Array} arr + * @return {Matrix} + */ +const jsonToMatrix = function(arr) { + let keySet = arr.reduce((keys, key) => { + getKeys(key).forEach(k => keys.add(k)); + return keys; + }, new Set()); + + let keys = Array.from(keySet).sort(); + + let matrix = [keys]; + arr.forEach(obj => { + matrix.push(keys.map(key => getValue(obj, key))); + }); + return matrix; +};