How to simplify a function that takes two parameters, an array of array objects and a string key, and returns an object with a structure
the function must return a structure of type.
{
array[0][key]: array[0],
array[1][key]: array[1],
_${key}s: [array[0][key], array[1][key]]
}
Here’s my function:
function (array, key) {
const result = {};
if (array == null || undefined) return "(((Not data)))";
for (let i = 0; i <= array.length - 1; i++) {
result[String(array[i][key])] = array[i];
}
const keys = {};
let keyArray = array.map((item) => String(item[key]));
keys[`_${key}s`] = keyArray.includes("undefined") ? [] : keyArray;
return {...result, ...keys };
}
Limitations and warranties:
– it is guaranteed that the key values of objects in the array (and nested objects) have only the following data types:
+string;
+number;
+null;
+undefined;
+ boolean;
– recommended time complexity of the function is O(n).
– the array parameter can take the values null or undefined – in this case, the function execution should not fail with an error.
– if the key argument is not among the keys of array objects, the function must return a structure of the form:
{
_${key}s: [];
}
I can’t fulfill the last condition including
2
Answers
Create an array of
[key, value]
usingArray.map()
, and then convert it to an object withObject.fromEntries()
. Check ifundefined
is a key on the object, and if not get the list of current keys usingObject.keys()
:Possibility with a
for...of
loop and using a negatedObject.hasOwn
call on the result to avoid adding duplicate keys to the_${key}s
array. Keep in mind that you have not indicated how duplicatearray[i][key]
values should be handled an so right now only the last object with any given value will be kept in the result.Note that
== null
will match bothnull
andundefined
see: What’s the difference between a == null and a === null?.