skip to Main Content

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


  1. Create an array of [key, value] using Array.map(), and then convert it to an object with Object.fromEntries(). Check if undefined is a key on the object, and if not get the list of current keys using Object.keys():

    function fn(array, key) {
      if (!array) return "(((Not data)))";
      
      const obj = Object.fromEntries(array.map(o => [o[key], o]));
      
      return {
        ...obj,
        [`_${key}s`]: 'undefined' in obj ? [] : Object.keys(obj)
      };
    }
    
    console.log(fn([{ a: 1 }, { a: 2 }, { a: 3 }, { a: 4 }], 'a'));
    console.log(fn([{ a: 1 }, { a: 2 }, {}], 'a'));
    Login or Signup to reply.
  2. Possibility with a for...of loop and using a negated Object.hasOwn call on the result to avoid adding duplicate keys to the _${key}s array. Keep in mind that you have not indicated how duplicate array[i][key] values should be handled an so right now only the last object with any given value will be kept in the result.

    function mapByKey(array, key) {
      if (array == null) {
        return `Invalid array`;
      }
    
      const result = { [`_${key}s`]: [] };
    
      for (const o of array) {
        if (Object.hasOwn(o, key)) {
          const keyValue = o[key].toString();
    
          if (!Object.hasOwn(result, keyValue)) {
            result[`_${key}s`].push(keyValue);
          }
    
          result[keyValue] = o;
        }
      }
    
      return result;
    }
    
    console.log(mapByKey(undefined, true));
    console.log(mapByKey(null, "keys"));
    console.log(mapByKey([], true));
    console.log(mapByKey([{ stringKey: 1 }, { stringKey: 2 }], "stringKey"));
    console.log(mapByKey([{ 1: "one" }, { 1: "one" }, { 1: "two" }], 1));
    console.log(mapByKey([{ false: "one" }, { false: "two" }, { true: "three" }], false));

    Note that == null will match both null and undefined see: What’s the difference between a == null and a === null?.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search