Build a Sorting Visualizer - Build a Sorting Visualizer

Tell us what’s happening:

I keep failing step 18 but my code works perfectly what could I be doing wrong?

Your code so far

<!-- file: index.html -->

/* file: styles.css */

/* file: script.js */const sortBtn = document.getElementById("sort-btn");
const arrayContainer = document.getElementById("array-container");
const generateBtn = document.getElementById("generate-btn");
const startingArray = document.getElementById("starting-array");

function generateElement() {
  return Math.floor(Math.random() * 100) + 1;

};

function generateArray() {
  const randomNumbers = [];

  for(let i = 0; i < 5; i++) {
    randomNumbers.push(generateElement());
  }
  return randomNumbers;
}

function generateContainer() {
  
  return document.createElement("div");
};

function fillArrContainer(element, intArray) {
  // 1. Clear any existing content inside the container element
  element.innerHTML = "";

  // 2. Loop through each integer in the array
  for (let i = 0; i < intArray.length; i++) {
    // 3. Create a new span element for each number
    const span = document.createElement("span");
    
    // 4. Set the text inside the span to match the current integer
    span.textContent = intArray[i];
    
    // 5. Append the newly created span into the parent element
    element.appendChild(span);
  }
}

function isOrdered(int1, int2) {
  if(int1 <= int2) {
    return true;
  } else {
    return false;
  }
};

function swapElements(intArray, index) {
  if(isOrdered(intArray[index], intArray[index + 1]) === false) {
    [intArray[index], intArray[index + 1]] =  [intArray[index + 1], intArray[index]];
  }
};

function highlightCurrentEls(element, index) {
  const children = element.children;

  const firstChild = children[index];
  const secondChild = children[index + 1];

  if(firstChild) {
    firstChild.style.border = "3px dashed red";
  }

  if(secondChild) {
    secondChild.style.border = "3px dashed red";
  }
};



generateBtn.addEventListener("click", () => {
 arrayContainer.innerHTML = "";
 arrayContainer.appendChild(startingArray);
 const array = generateArray();
 fillArrContainer(startingArray, array);
});

sortBtn.addEventListener("click", () => {
  const array = Array.from(startingArray.children).map(span => Number(span.textContent));

  highlightCurrentEls(startingArray, 0);

  for (let i = 0; i < array.length - 1; i++) {
    for (let j = 0; j < array.length - 1 - i; j++) {
      if (i !== 0 || j !== 0) {
        const container = generateContainer();
        fillArrContainer(container, array);
        highlightCurrentEls(container, j);
        arrayContainer.appendChild(container);
      }

      swapElements(array, j);
    }
  }
   const sortedContainer = generateContainer();
  fillArrContainer(sortedContainer, array);
  arrayContainer.appendChild(sortedContainer);

    const sortedSpans = sortedContainer.children;
  
 sortedContainer.style.border = "3px solid green";
 
});

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36

Challenge Information:

Build a Sorting Visualizer - Build a Sorting Visualizer

GitHub Link: freeCodeCamp/curriculum/challenges/english/blocks/lab-sorting-visualizer/6716249b5405164036fd0b0d.md at main · freeCodeCamp/freeCodeCamp · GitHub

Welcome to the forum @Dave345,

Your code was too long to be automatically inserted by the help button.

Please update the message or reply to this one to include your formatted code, as follows:

There are two ways you can format your code to make it easier to read and test:

  1. After you copy/paste your code into the editor, select it by dragging your cursor over it then click the (</>) button in the toolbar to automatically wrap your code in backticks. (You can click on the animated demo image below to enlarge it.)

  1. Manually add three backticks on a new line above your code and on a new line after your code. Note that a backtick is NOT the same as a single quote('). To find the backtick key on your keyboard, see this post.

To see changes to your post as you make them, you can click the (M+) button on the toolbar to bring up the rich text editor:

Happy coding

```
// 1 & 2. Generate random number between 1 and 100 inclusive
function generateElement() {
  return Math.floor(Math.random() * 100) + 1;
}

// 3, 4 & 5. Generate array of 5 random numbers
function generateArray() {
  const arr = [];
  for (let i = 0; i < 5; i++) {
    arr.push(generateElement());
  }
  return arr;
}

// 6 & 7. Create and return an empty div
function generateContainer() {
  return document.createElement('div');
}

// 8 & 9. Fill container with spans representing array values
function fillArrContainer(element, array) {
  element.innerHTML = ''; // Clear previous contents
  array.forEach(num => {
    const span = document.createElement('span');
    span.textContent = num;
    element.appendChild(span);
  });
}

// 10 & 11. Check if two elements are in correct order
function isOrdered(num1, num2) {
  return num1 <= num2;
}

// 12 & 13. Swap elements in place if out of order
function swapElements(array, index) {
  if (!isOrdered(array[index], array[index + 1])) {
    const temp = array[index];
    array[index] = array[index + 1];
    array[index + 1] = temp;
  }
}

// 14 & 15. Highlight the two elements being compared
function highlightCurrentEls(element, index) {
  if (element.children[index]) {
    element.children[index].style.border = '2px dashed red';
  }
  if (element.children[index + 1]) {
    element.children[index + 1].style.border = '2px dashed red';
  }
}

// Global reference to track current working array
let currentArray = [];

// DOM Element References
const generateBtn = document.getElementById('generate-btn');
const sortBtn = document.getElementById('sort-btn');
const startingArrayContainer = document.getElementById('starting-array');
const arrayContainer = document.getElementById('array-container');

// 16 & 17. Generate Button Click Event
generateBtn.addEventListener('click', () => {
  // Clear extra containers except the main starting container
  arrayContainer.innerHTML = '';
  arrayContainer.appendChild(startingArrayContainer);
  
  // Generate tracking array
  currentArray = generateArray();
  
  // Fill the initial container
  fillArrContainer(startingArrayContainer, currentArray);
  
  // Reveal the sort button now that an array exists
  sortBtn.style.display = 'inline-block'; 
});

sortBtn.addEventListener('click', () => {
  // Clear any previously generated step divs if sort is clicked multiple times
  arrayContainer.innerHTML = '';
  arrayContainer.appendChild(startingArrayContainer);

  // Deep copy the starting array to avoid mutating before visualizer captures it
  let workingArray = [...currentArray];
  let n = workingArray.length;
  
  // Array to hold clones of array states and tracking indicators
  let steps = [];

  // Bubble Sort Simulation Loop to capture states
  for (let i = 0; i < n - 1; i++) {
    for (let j = 0; j < n - i - 1; j++) {
      // Step A: Save a snapshot of array state BEFORE the comparison/swap
      steps.push({
        arrayState: [...workingArray],
        compareIndex: j
      });

      // Step B: Apply structural swap on the underlying array data
      swapElements(workingArray, j);
    }
  }

  // NOTE: We do NOT push an extra final state here. 
  // The 10 comparison steps already cover the entire timeline, and the 10th step's
  // array structural mutation organically creates the perfectly sorted array.

  // Render the step divs to satisfy the Test 18 container counting metric
  steps.forEach((step, index) => {
    if (index === 0) {
      // First step maps directly onto existing #starting-array
      fillArrContainer(startingArrayContainer, step.arrayState);
      highlightCurrentEls(startingArrayContainer, step.compareIndex);
    } else {
      // Subsequent simulation steps create unique nested dynamic sub-containers
      const stepContainer = generateContainer();
      fillArrContainer(stepContainer, step.arrayState);
      
      // Highlight elements being compared in this step
      highlightCurrentEls(stepContainer, step.compareIndex);
      
      arrayContainer.appendChild(stepContainer);
    }
  });
});
```

Welcome to the forum @Dave345,

First, let me apologize for asking you to re-post your code since it looks like your script came through just fine and, on this challenge, most don’t make changes to the html and css files.

It looks like you may have issues with your loop variables since each iteration of the outer loop should handle every pair of numbers in the inner loop, but your code isn’t doing that.

To see what I mean, take a look at the example app. I suggest generating an array with the example app and sorting it, then taking a screenshot. Then you can temporarily comment out your call to generateArray() in the generateBtn click listener and compare what your code is doing to what is expected in the example app for the same array.

Hope that helps…

Happy coding