I have an array like this
students = [{name: 'Abbey', age: 25}, {name: 'Brian', age: 45}, {name: 'Colin', age: 25}, {name: 'Dan', age: 78}]
and I want the output to be:
uniqueAges = [45, 78]
To be clear, if there is an age value that appears several times in the students array, I do not want any objects with this age in my uniqueAges array. Abbey and Colin are of the same age, so both of them .
I know I can do something like this and run uniqueAgeGetter(students)
function uniqueAgeGetter(list){ var listCopy = list.slice(); var uniqueAges = list.slice(); for (var i = list.length - 1; i >= 0; i--) { for (var j = listCopy.length - 1; j >= 0; j--) { if(listCopy[j].name !== list[i].name && listCopy[j].age == list[i].age){ uniqueAges.splice(i, 1) } } } console.log(uniqueAges) return uniqueAges }
But can this be done without a second cycle? I am not a specialist in time complexity, but I'm trying to find out if it is possible that this task can be O (n).
Edit: I am not asking if it is possible to rewrite uniqueAgeGetter to read better or use functions like map, reduce or filter (since, as I understand it, they are ultimately loops).
My question is, can uniqueAgeGetter be reorganized in such a way as to reduce time complexity? Can this be done with just one loop?
Thanks.