I
I
ivanDoligov2020-04-13 18:31:50
JavaScript
ivanDoligov, 2020-04-13 18:31:50

How to write code correctly without mutating sort?

Hello, friends! please tell me how to rewrite the code that contained the mutating sort method to the code without it (maybe using map)?

const age = person.sort((item1, item2) => (item1.age - item2.age));

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Tigran Abrahamyan, 2020-04-13
@ivanDoligov

const age = person => {
  let amount;

  for (let i = 0; i < person.length; i++) {
    for (let j = i; j < person.length; j++) {
      if (person[i] > person[j]) {
        amount = person[i];
        person[i] = person[j];
        person[j] = amount;
      }
    }
  }

  return person;
}

const res = [3, 4, 2, 78, 0, 1];

console.log(age(res));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question