3

I am trying to iterate over an array of array objects to de-dupe and sort the data within each. The function onlyUnique returns unique values in an array. The problem is, it doesn't work as intended.

arr_lists = [arr_1, arr_2, arr_3, arr_4, arr_5, ...]

for (var list_obj of arr_lists) {
  list_obj = list_obj.join().split(',').filter(onlyUnique);
  list_obj.sort();
  Logger.log(list_obj);
}

The logger results show true (i.e. they are what I am looking for), but the original array is unchanged, although I think it should have been updated.

I've tried assigning the filtered array to a new array... nope. I know that I could add a thousand lines of code to achieve the results, but that seems silly.

I suspect it's something obvious.

3
  • 1
    the list_obj = ... line inside the loop reassigns list_obj to be a new array, so it is no longer a reference to one in the array. So sorting that array doesn't do anything to the original array. Commented Nov 5, 2022 at 22:52
  • 1
    split(',') creates a new array, and filter creates again a new array. Your code is not sorting the original array. Unrelated, but why do you do .join().split(',')? Commented Nov 5, 2022 at 22:54
  • @trincot, great question. Frankly, I don't know. I lifted the .join().split(',') code while looking for an easy way to filter to unique values in a list. I never examined the logic at the time. Commented Nov 10, 2022 at 15:03

1 Answer 1

1

You can simply achieve it by using Set data structure to remove the duplicates and Array.sort() compare function to sort the elements in an array.

Live Demo :

const arr_lists = [[2,3,5,6], [7,2,5,3,3], [1,5,3], [4,7,4,7,3], [1,2,3]];

arr_lists.forEach((arr, index) => {
  arr_lists[index] = [...new Set(arr)].sort((a, b) => a -b);
})

console.log(arr_lists);

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.