배열에서 유일한 값만 추리기 (Get only unique values in an array)
기본 알고리즘
const source = [1, 2, 3, 2, 4, 5, 3, 3, 7];
for (let indexLeader = 0, lengthLeader = source.length; indexLeader < lengthLeader; indexLeader += 1) {
// console.group(`leader index${indexLeader}`, source[indexLeader], source);
for (let indexFollower = indexLeader + 1, lengthFollower = source.length; indexFollower < lengthFollower; indexFollower += 1) {
// console.log('follower', indexFollower, source[indexFollower]);
if (indexLeader === indexFollower) continue;
if (source[indexLeader] === source[indexFollower]) {
// console.log('-deleted', indexFollower, source[indexFollower], source);
source.splice(indexFollower, 1);
// console.log('*after deleted', indexFollower, source);
indexLeader -= 1;
indexFollower -= 1;
lengthLeader -= 1;
lengthFollower -= 1;
}
}
// console.groupEnd(`index${indexLeader}`);
}
=> [1, 2, 3, 4, 5, 7]
단순화
const source = [1, 2, 3, 2, 4, 5, 3, 3, 7];
source.filter((value, index, self) => (self.indexOf(value) === index));
=> [1, 2, 3, 4, 5, 7]
댓글
댓글 쓰기