-1

I've got what seems to be a fairly simple JavaScript function that I'm implementing in my vuex store, but the function seems to be behaving asynchronously; using console.log() [in chrome] gets me the full array, but trying console.log(JSON.parse(JSON.stringify(array))) gives me an empty array. From what little I know, this suggests that some part of my code is behaving asynchronously, and I'd really like to figure out how to alter this behavior to be synchronous.

My code:

function groupBy(array, key){
    let list = [];
    array.forEach(element =>{
        if(!list[element[key]]){
            list[element[key]] = [element];
        }else{
            list[element[key]].push(element);
        }
    });
    return list;
}

I'm testing the output with this:

    let list = groupBy(items, 'grpstr');
    console.log(JSON.parse(JSON.stringify(list)));
    console.log(list);
    return list;

Again, in the chrome console the first log() is returning an empty array, while the second is returning the proper array. What's my mistake here?

I've tried changing the accumulated array to an object, which works (strangely), but I need to pass this array into the vuejs app to be iterated over and vue doesn't iterate over object keys in a useful fashion (for my app, at least).

EDIT: the data being passed to the function is an array of objects of the form:

[{grpstr: "01-31-2017" ...}, {grpstr: "01-31-2017" ...}, {grpstr: "01-31-2017" ...} ]

1 Answers1

0

This has nothing todo with asynchrony. Don't use arrays as objects. When serializing an array, all non numeric properties get removed, thats why they don't occur in your first log. Generally arrays are meant to be used with numeric keys, so an object is a better choice here (as your keys are non numeric).

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151