0

I'm trying to store duplicate arrays into a new array but I keep on getting an empty array in the console. Please help.

function removedIntegers(arr) {
  let sortedArr = arr.sort();
  let j = [];
  for (let i = 0; i < sortedArr.length; i++) {
    if (sortedArr[i] != sortedArr[i + 1]) {
      j.push(sortedArr[i]);
    }
  }
  return j;
}
2
  • Could you please say what language this is (so we know the scoping rules for variables) and show the program that calls removedIntegers. Commented Nov 17, 2021 at 19:31
  • could you share how you are invoking this function and the array you are using, it worked for me when I put your function in a js fiddle. Commented Nov 17, 2021 at 19:31

1 Answer 1

2

Though your code is working fine,

let years = [2020,2020,2021,2021,2022,2023,2024,2025,2026,2027]
function removedIntegers(arr) {
  let sortedArr = arr.sort();
  let j = [];
  for (let i = 0; i < sortedArr.length; i++) {
    if (sortedArr[i] != sortedArr[i + 1]) {
      j.push(sortedArr[i]);
    }
  }
  return j;
}

console.log(removedIntegers(years))

In ES6, the code is simpler than before for duplicate removal.

let years = [2020,2020,2021,2021,2022,2023,2024,2025,2026,2027]
function sortAndUnique(arr){
return [...new Set(arr.sort())]
}

console.log(sortAndUnique(years))

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.