I'm trying to replicate this selection sort for loop using a for... of loop. I've worked on transitioning it for awhile now, however, nothing that I've tried has worked. Is this possible?
Array set:
var fruits = ["Apple", "Banana", "Carrot", "Guava", "Orange"];
Traditional for loop
for (var i = 0; i < fruits; i ) {
let outerItem = fruits[i];
for (var j = i 1; j < fruits.length; j ) {
let innerItem = fruits[j];
if (innerItem == outerItem) {
innerItem.length > outerItem.length ? fruits.splice(fruits.indexOf(outerItem), 1) :
fruits.splice(fruits.indexOf(innerItem), 1);
}
}
}
for...of loop
for(let outerItem of fruits)
{
for(let innerItem of fruits)
{
}
}
CodePudding user response:
To fast replicate an array, use slice: const sliced = fruits.slice();
The below shows the solution of Traditional for loop
and for...of loop
on a given array var fruits = ["Apple", "Banana", "Carrot", "Guava", "Orange"];
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
const writeln = (text = '') => document.writeln(text '<br/>');
</script>
<script>
var fruits = ["Apple", "Banana", "Carrot", "Guava", "Orange"];
writeln(fruits);
writeln();
writeln('Slice');
const sliced = fruits.slice();
writeln(sliced);
writeln();
writeln('Traditional for loop');
const copy = [];
for (var i = 0; i < fruits.length; i ) {
copy.push(fruits[i]);
}
writeln(copy);
writeln();
writeln('for...of loop');
const copy1 = [];
for (const value of fruits) {
copy1.push(value);
}
writeln(copy1);
</script>
</body>
</html>