0

My task was to convert array to object using loops.

arr = ['a', 'b', 'c', 'd', 'e']; 

to object array

arr = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5};

I got the right result, but I am not sure about the way I was solving this task. Please give me a piece of advice.

let arr = ['a', 'b', 'c', 'd', 'e'];
let obj = {};
for (let i = 0; i < arr.length; i++) {
  obj[arr[i]] = i + 1
}

console.log(obj)

As I mentioned before, the result is right

{ a: 1, b: 2, c: 3, d: 4, e: 5 }

But I tend to feel that there is a better solution.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • 4
    If your task was to create an object from an array using a loop that's a good solution. – Andy Oct 30 '19 at 09:21
  • The answer depends on how you want to handle edge cases like arrays with holes `['a', 'b',,,,,,,'c']` or with duplicate elements `['a', 'b', 'a', 'c']` – georg Oct 30 '19 at 09:27

3 Answers3

0

One option is to transform the arr into an array of entries, using the index to specify the value, then use Object.fromEntries to turn it into an object:

let arr = ['a', 'b', 'c', 'd', 'e'];
const obj = Object.fromEntries(
  arr.map((prop, i) => [prop, i + 1])
);
console.log(obj);

(though, Object.fromEntries is a relatively new method)

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Can that be considered "using loops"? – Andy Oct 30 '19 at 09:22
  • *Anything* involving iteration uses a loop somewhere, though OP can clarify if he doesn't want to use functional methods – CertainPerformance Oct 30 '19 at 09:24
  • They probably won't know not to exclude functional methods because I doubt they're that far into the course(?) to know what they are. A "loop" has a very specific meaning at that early stage. – Andy Oct 30 '19 at 09:26
0

You could take a while statement and increment i only once.

var array = ['a', 'b', 'c', 'd', 'e'];
    object = {},
    i = 0;

while (i < array.length) object[array[i]] = ++i;

console.log(object);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You could use Array#reduce to accomplish this.

  1. Initially set the accumulator to an empty object {}
  2. For each iteration use spread syntax on the accumulator in a new object
  3. Then add a new property to this new object which will be your currrent and set the value to i (the current index) + 1.
  4. Return the new accumulator
  5. Repeat till end of the list

const arr = ['a', 'b', 'c', 'd', 'e'];

const res = arr.reduce((acc,cur,i)=>({...acc, [cur]:i+1}), {});

console.log(res);

Verbose solution without spread operator:

const arr = ['a', 'b', 'c', 'd', 'e'];

const res = arr.reduce((acc,cur,i)=>{
  acc[cur] = i + 1;
  return acc;
}, {});

console.log(res);
kemicofa ghost
  • 16,349
  • 8
  • 82
  • 131