0

I want to be able to access an array so that I can loop over it either manually or with a forEach function etc. Currently I am getting an Array of length 0 however it does have objects with in it accessed by array.name. Alternatively I wouldn't mind keeping the current data structure if I knew how to loop through it. Here is my code:

Edit - I should probably be looking at key/value pairs?

var renameFiles = function renameFiles(files) {
  var map = [];
  var reg = /\(\d+\)/;

  files.filter(function(file) {

    if(!map[file.replace(reg, '')]) {
      map[file.replace(reg, '')] = [file];
    } else if (!map[file] && !file.match(reg)) {
      map[file] = [file];
    } else if (map[file.replace(reg, '')]) {
      map[file.replace(reg, '')].push(file);
    } else {
      map[file].push(file);
    }
  });

  return map;
};

f = ['a(1)', 'a(6)', 'a','a','a','b','b(1)','b(4)','c','c(2)'];
pauld
  • 401
  • 1
  • 5
  • 20
  • What are you trying to achieve exactly? you current function has an odd output: an array with key-value store. Do you want something like: { a: [a, a, a, a(1), a(6)], b: [b, b(1), b(4)], c: [c, c(2)] } ? Or maybe you want an array of arrays. I have a hard time trying to understand what renameFiles function does exactly (it doesn't seem to rename anything for some reason) – tudor.gergely Apr 15 '16 at 05:17
  • the output is just temporary, the point is to rename all duplicate files - just had a brain fart about how to work with key values... – pauld Apr 15 '16 at 05:19

1 Answers1

0

You could you for(var key in map) or Object.keys(map) to loop it. Here is a sample code:

var map = [];
map['a'] = '1';
map['b'] = '2';
map['c'] = '3';


console.log(map.length == 0);

for(var key in map) {
  console.log('map[' + key +'] = ' + map[key]);
}
Ricky Jiao
  • 531
  • 4
  • 10
  • It does not work. of keyword only works in iterable object. Here is a workaround solution: http://stackoverflow.com/questions/29885220/using-objects-in-for-of-loops. BTW, of only works in ES6 which is not support in IE. – Ricky Jiao Apr 15 '16 at 05:29