I have one array of element IDs on the page but this array is not sorted by their position in DOM/page. I want to sort them by their position on the page.
Array:
[{ id:'first', type:'TEXT'},{id:'third',type:'DROPDOWN'},{id:'second',type:'TEXT'}]
output:
[{id:'first', type:'TEXT'},{id:'second',type:'TEXT'},{id:'third',type:'DROPDOWN'}]
CodePudding user response:
I can propose this solution if you want to take it:
let input = [
{ id: 'second', type: 'TEXT' },
{ id: 'third', type: 'DROPDOWN' },
{ id: 'first', type: 'TEXT' },
];
output = [];
for (let i = 0; i < input.length; i ) {
if (input[i].id === 'first') {
input[i].position = 1;
}
if (input[i].id === 'second') {
input[i].position = 2;
}
if (input[i].id === 'third') {
input[i].position = 3;
}
}
output = input.sort(function (a, b) {
return a.position - b.position;
});
here's the result of console log output
let input = [
{ id: 'second', type: 'TEXT' },
{ id: 'third', type: 'DROPDOWN' },
{ id: 'first', type: 'TEXT' },
];
output = [];
for (let i = 0; i < input.length; i ) {
if (input[i].id === 'first') {
input[i].position = 1;
}
if (input[i].id === 'second') {
input[i].position = 2;
}
if (input[i].id === 'third') {
input[i].position = 3;
}
}
output = input.sort(function (a, b) {
return a.position - b.position;
});
console.log(output);
CodePudding user response:
A generic approach which works across any DOM structure might look similar to the next provided example code ...
const unorderedReferenceList = [
{ id: 'bar', type: 'TEXT' },
{ id: 'baz', type: 'DROPDOWN' },
{ id: 'foo', type: 'TEXT' },
];
console.log({ unorderedReferenceList });
const referenceIndex = unorderedReferenceList
.reduce((index, reference) => {
index[reference.id] = reference;
return index;
}, {});
console.log({ referenceIndex });
const elementList = Array.from(
document.body.getElementsByTagName('div')
);
console.log({ elementList });
const filteredElementList = elementList
.filter(function (elm) {
return (elm.id in this);
}, referenceIndex);
console.log({ filteredElementList });
const orderedReferenceList = filteredElementList
.map(function (elm) {
return this[elm.id];
}, referenceIndex);
console.log({ orderedReferenceList });
.as-console-wrapper { min-height: 100%!important; top: 0; }
<div>
<div>
<div>
<div>
<div></div>
<div id="foo">foo</div>
</div>
<div id="bar">bar</div>
</div>
</div>
<div>
<div>
<div id="baz">baz</div>
<div></div>
</div>
</div>
</div>