At the start of the first iteration (index equals 0), your code appears as follows
hos.map((item, index) => {
console.log(index);
// neither hos[1] nor hos[-1] exist -> undefined
if (item.Driver == hos[0+1] || item.Driver == hos[0-1].Driver) {
hosByDriver[item.Driver].push(item);
} else {
hosByDriver[item.Driver].push(item);
}
});
This leads to a crash at the very beginning. The expression hos[0-1].Driver
results in undefined.Driver
. To avoid this issue, you can use &&.
Note: array[-1] is not invalid syntax
hos[index - 1] && hos[index - 1].Driver
Furthermore, keep in mind that item.Driver is a string. Arrays are usually indexed by numbers, so it seems like you intended to use an Object instead:
let hosByDriver = {};
hos.forEach((item, index) => {
console.log(index);
if (hos[index - 1] && (item.Driver === hos[index + 1] || item.Driver === hos[index - 1].Driver)) {
//hosByDriver[item.Driver] = [];
//hosByDriver[item.Driver].push(item);
} else {
hosByDriver[item.Driver] = [];
hosByDriver[item.Driver].push(item);
}
});
The change from .map to .forEach was made since you are not generating a new Array to return. If only iterating is needed, forEach is more appropriate.
Based on my assumptions regarding your goal, I have provided a suggested solution. For further clarification, additional details would be beneficial. Check out the codesandbox link for reference:
https://codesandbox.io/s/stackoverflow-3h2n9
It may be helpful to brush up on fundamental JavaScript concepts such as data types and loops. Keep learning! :)
Update:
If my understanding is correct, you aim to group Drivers in hosByDriver based on matching names stored in hos. This grouping allows easy access to all items of a driver like hosByDriver['test-000000']
without repetitive array iterations.
You can accomplish this efficiently as follows
let hosByDriver = {};
hos.forEach(item => {
// Check if item or item.Driver may deviate from expectations
// with conditional statement:
// item && item.Driver && typeof item.Driver === "string"
if(!hosByDriver[item.Driver]){
hosByDriver[item.Driver] = [];
}
hosByDriver[item.Driver].push(item);
});
Additional Information:
In JavaScript, Arrays are essentially Objects with key/value pairs. For more insight, consider watching JavaScript: Understanding the Weird Parts. While arrays allow indexing with numbers starting from zero, using strings in place should be avoided for clarity and easier debugging.
It is advised to refrain from using == and opt for === to prevent unintended type conversions. For instance, 0 == ""
evaluates to true
, leading to potential complications and errors.