4👍
✅
Try to add let i before using it in the for loop.
See example below.
for (let i in newArray) {
if (i.version.startsWith('iPad')) {
newlist.push(newlist.splice(i, 1)[0]);
}
}
0👍
Several problems with the original code.
- The missing
const
/let
oni
in
loop should beof
. Or maybe not. The following lines seem to assume thati
is both the index and the entry.newlist
isn’t defined.- It seems to be trying to mutate an array whilst iterating over it.
I think you’re looking for something more like this.
const newArray = sortBy(getData(), 'version').reverse()
const nonIPads = []
const iPads = []
for (const entry of newArray) {
if (entry.version.startsWith('iPad')) {
iPads.push(entry)
} else {
nonIPads.push(entry)
}
}
const all = [...nonIPads, ...iPads]
console.log(all)
function sortBy(array, property) {
return [...array].sort((a, b) => {
const valueA = a[property]
const valueB = b[property]
if (valueA === valueB) {
return 0
}
return valueA < valueB ? -1 : 1
})
}
function getData() {
return [
{version: 'f'},
{version: 'a'},
{version: 'd'},
{version: 'iPad 3'},
{version: 'iPad 1'},
{version: 'iPad 4'},
{version: 'e'},
{version: 'c'},
{version: 'g'},
{version: 'b'},
{version: 'iPad 2'}
]
}
Source:stackexchange.com