Home > Net >  How can I loop 2D array and modify its values
How can I loop 2D array and modify its values

Time:10-09

Given 2D array of photos taken while John doe was on trips so I'm asked to rename pictures and replace actual name with city name where a picture was taken.

const photos = [
['photo.jpg', 'kigali','2013-09-05 14:08:09'],
['demmpa.jpg', 'kigali','2013-09-05 14:08:09'],
['third.jpg', 'kibuye','2013-02-05 12:08:09']
['forthpic.jpg', 'kampala','2013-02-05 12:08:09']
]
   photos.map((photo, index)=>{
    photo.filter((photo, index)=> console.log(photo))
    
  })

Actual output

"photo.jpg"
"kigali"
"2013-09-05 14:08:09"
"demmpa.jpg"
"kigali"
"2013-09-05 14:08:09"

Expected output

kigali01.jpg
kigali02.jpg
Kibuye1.jpg
kampala1.jpg

CodePudding user response:

You can do it using map. And the occurrence will just keep the number of how many times the name is repeated.

Note: if you need to add leading zeros, Please check it out How to output numbers with leading zeros in JavaScript?

const photos = [
  ['photo.jpg', 'kigali','2013-09-05 14:08:09'],
  ['demmpa.jpg', 'kigali','2013-09-05 14:08:09'],
  ['third.jpg', 'kibuye','2013-02-05 12:08:09'],
  ['forthpic.jpg', 'kampala','2013-02-05 12:08:09']
];

const occurrence = {}

const newArray = photos.map(arr => {

  const ext = arr[0].split('.')[1]; // file extension

  if (occurrence[arr[1]]) { // check whether the name is already there
    occurrence[arr[1]]  ;
    return `${arr[1]}${occurrence[arr[1]]}.${ext}`;
  }
  
  occurrence[arr[1]] = 1;
  return `${arr[1]}1.${ext}`;

});


console.log(newArray)

CodePudding user response:

let photos = [
['photo.jpg', 'kigali','2013-09-05 14:08:09'],
['demmpa.jpg', 'kigali','2013-09-05 14:08:09'],
['third.jpg', 'kibuye','2013-02-05 12:08:09'],
['forthpic.jpg', 'kampala','2013-02-05 12:08:09']
]

 photos = Array.from(photos).map((photo)=>{
 const format = photo[0].split('.')[1]
 photo[0]=photo[1] '.' format
 return photo
})
  • Related