-3

i want to print index and its element side by side in JS and C++. like this:

arr = [1,2,3,4,5]
[ {0 : 1},
{1 : 2},
{2 : 3},
{3 : 4},
{4 : 5} ]

I have done like this, but not able to

const arr = [1,2,3,4,5]

for (let i = 0; i < arr.length; i++) {
  let obj = {};
  let emptArr = [];
  obj.i = arr[i];
  emptArr.push(obj);
  console.log(emptArr);
}
Andy
  • 61,948
  • 13
  • 68
  • 95
Mark
  • 67
  • 6

2 Answers2

-1

You are creating a new array each time

Here is how to store the object with the index as the key string. You cannot have a numeric key

const arr = [1,2,3,4,5];
const newArr = arr.map((val,i) => ({[i]:val}));
console.log(newArr);

Here is your code fixed

const arr = [1,2,3,4,5];
const emptArr = [];
for (let i = 0; i < arr.length; i++) {
  let obj = {};
  obj[i] = arr[i];
  emptArr.push(obj);
}
console.log(emptArr);
mplungjan
  • 169,008
  • 28
  • 173
  • 236
-1

here is with map

const arr = [1,2,3,4,5];

const newArr = arr.map((value, index) => {
  return {
    [index]: value
  }
})

console.log(newArr)
Mohit Sharma
  • 622
  • 6
  • 11