freeCodeCamp/curriculum/challenges/portuguese/10-coding-interview-prep/rosetta-code/hash-from-two-arrays.md

2.4 KiB

id title challengeType forumTopicId dashedName
595671d4d2cdc305f0d5b36f Hash from two arrays 5 302283 hash-from-two-arrays

--description--

Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values).

Related task:

--hints--

arrToObj should be a function.

assert(typeof arrToObj === 'function');

arrToObj([1, 2, 3, 4, 5], ["a", "b", "c", "d", "e"]) should return { 1: "a", 2: "b", 3: "c", 4: "d", 5: "e" }

assert.deepEqual(arrToObj(...testCases[0]), res[0]);

arrToObj([1, 2, 3, 4, 5], ["a", "b", "c", "d"]) should return { 1: "a", 2: "b", 3: "c", 4: "d", 5: undefined }

assert.deepEqual(arrToObj(...testCases[1]), res[1]);

arrToObj([1, 2, 3], ["a", "b", "c", "d", "e"]) should return { 1: "a", 2: "b", 3: "c" }

assert.deepEqual(arrToObj(...testCases[2]), res[2]);

arrToObj(["a", "b", "c", "d", "e"], [1, 2, 3, 4, 5]) should return { "a": 1, "b": 2, "c": 3 , "d": 4, "e": 5 }

assert.deepEqual(arrToObj(...testCases[3]), res[3]);

arrToObj(["a", "b", "c", "d", "e"], [1, 2, 3, 4]) should return { "a": 1, "b": 2, "c": 3 , "d": 4, "e": undefined }

assert.deepEqual(arrToObj(...testCases[4]), res[4]);

arrToObj(["a", "b", "c"], [1, 2, 3, 4, 5]) should return { "a": 1, "b": 2, "c": 3 }

assert.deepEqual(arrToObj(...testCases[5]), res[5]);

--seed--

--after-user-code--

const testCases = [
  [[1, 2, 3, 4, 5], ['a', 'b', 'c', 'd', 'e']],
  [[1, 2, 3, 4, 5], ['a', 'b', 'c', 'd']],
  [[1, 2, 3], ['a', 'b', 'c', 'd', 'e']],
  [['a', 'b', 'c', 'd', 'e'], [1, 2, 3, 4, 5]],
  [['a', 'b', 'c', 'd', 'e'], [1, 2, 3, 4]],
  [['a', 'b', 'c'], [1, 2, 3, 4, 5]]
];

const res = [
  { 1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e' },
  { 1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: undefined },
  { 1: 'a', 2: 'b', 3: 'c' },
  { a: 1, b: 2, c: 3, d: 4, e: 5 },
  { a: 1, b: 2, c: 3, d: 4, e: undefined },
  { a: 1, b: 2, c: 3 }
];

--seed-contents--

function arrToObj (keys, vals) {

  return true;
}

--solutions--

function arrToObj (keys, vals) {
  return keys.reduce((map, key, index) => {
    map[key] = vals[index];
    return map;
  }, {});
}