I am trying to create a list of values from a sorted array that will automatically generate a DOM element for each unique object inside of the sorted array.
I have a JSFiddle here since it requires DOM: https://jsfiddle.net/o09aenby/1/
Array of objects is generated with
// random value for the sake of unique objects
let randomVal = Math.floor(Math.random() * 100);
const data = {
value: randomVal
}
array.push(data);
let sortedValues = (array) => {
return array.sort((a, b) => {
return b.value - a.value;
})
}
sortedArray = sortedValues(array);
I loop through the sorted array and create a DOM element with this for loop
let displayData = [];
displayData = sortedArray;
for (let i = 0; i < displayData.length; i ) {
let element = document.createElement('p');
element.classList.add('data-output', 'node');
element.innerHTML = `Value: ${data.value}`
list.append(element);
}
The goal is to keep the array of data because I will be saving it to a localStorage JSON and populating based off of the JSON later, so the data of the array needs to be preserved.
I have tried using forEach but also couldn't manage to get it to work.
CodePudding user response:
You never update data
here:
element.innerHTML = `Value: ${data.value}`
so you are setting every element to the same value. You need to do
element.innerHTML = `Value: ${displayData[i].value}`