Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

103
Views
Why massToMove is undefined

Hello I want to return massToMove from my algorithm. But I get undefined, when I console.log() inside the loop I got the proper number. Why it is undefined and how can I prevent that? It is quiet weird because variable is defined '0' and changed inside the loop.

let numberOfElephants = 6;
let massOfElephants = [2400, 2000, 1200, 2400, 1600, 4000];
let startOrder = [1, 4, 5, 3, 6, 2];
let endOrder = [5, 3, 2, 4, 6, 1];

const sortElephants = (
  numberOfElephants,
  massOfElephants,
  elephantsOrder,
  proposedOrder
) => {
  const elephantObject = [];
  elephantsOrder.forEach((order, i) => {
    elephantObject.push({ [order]: massOfElephants[i] });
  });
  let massToMove = 0;

  for (let i = 0; i < numberOfElephants; i++) {
    for (let j = 0; j < numberOfElephants; j++) {
      if (startOrder[i] === proposedOrder[j]) {
        if (
          startOrder.indexOf(startOrder[i]) ===
          endOrder.indexOf(proposedOrder[j])
        )
          return;
        const indexOfCorrect = proposedOrder.findIndex(
          (num) => num === endOrder[j]
        );
        const itemAtGivenOrder = startOrder[indexOfCorrect];

        let isCorrect =
          endOrder.indexOf(itemAtGivenOrder) ===
          startOrder.indexOf(itemAtGivenOrder);

        let temp;
        temp = startOrder[indexOfCorrect];

        startOrder[indexOfCorrect] = startOrder[i];

        startOrder[i] = temp;

        const elephantAtGivenCorrectIndex = elephantObject.find(
          (elephant) => elephant[itemAtGivenOrder.toString()]
        );

        const startingElephant = elephantObject.find(
          (elephant) => elephant[startOrder[i]]
        );

        if (!isCorrect) {
          massToMove += startingElephant[startOrder[i]];
        } else {
          massToMove +=
            elephantAtGivenCorrectIndex[itemAtGivenOrder] +
            startingElephant[startOrder[i]];
        }
      }
    }
  }
  return massToMove;
};

console.log(sortElephants(numberOfElephants, massOfElephants, startOrder, endOrder));

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!