Managing a large datasource filled with objects can be challenging. My goal is to rearrange the order of objects in the array based on new values for each key. Whenever a new value for a key is found, I want the corresponding object to move to the top of the array. This way, the top elements in the array will always represent the different values that properties can have.
arr[0] = {name: john, age: 14, address: xxx}
arr[1] = {name: john, age: 14, address: xxx}
arr[2] = {name: marie, age: 14, address: xxx}
arr[3] = {name: marie, age: 14, address: xxx}
arr[4] = {name: john, age: 15, address: xxx}
The desired outcome would look like this:
arr[0] = {name: john, age: 14, address: xxx}
arr[1] = {name: marie, age: 14, address: xxx}
arr[2] = {name: john, age: 15, address: xxx}
arr[3] = {name: marie, age: 14, address: xxx}
arr[4] = {name: john, age: 14, address: xxx}
This example is simplified as the actual dataset may vary in keys, quantity, and values. To dynamically achieve this reordering, I am currently iterating through all objects, identifying new values for each key, storing them in an array of unique values, and moving the current object to the top of the array based on these new values. The process repeats for each object containing a new key value.
filterDS(dataSource){
let uniqueColumns;
let i = 0;
let j = 0;
let temp;
dataSource.forEach(data => {
let keys = Object.keys(data);
keys.forEach( key => {
console.log(key + ":" + data[key]);
uniqueColumns[key].push(data[key]);
temp = dataSource[i];
j = dataSource.indexOf(data);
dataSource[i] = dataSource[j];
dataSource[j] = temp;
i++
})
});
return dataSource;
}
However, I seem to encounter issues when trying to read undefined values. I have attempted to check for empty datasource, key values, and even the current object, but the problem persists. It seems to break when encountering an undefined or empty field. I am unsure of what mistake I might be making here.