๋๋ ์ด๊ฒ์ ๋ฐ์ค์์ ์ด๋ฏธ ๋ณด์ง ๋ชปํ๊ธฐ ๋๋ฌธ์ ์ด๊ฒ์ ๊ฑฐ๊ธฐ์ ๋์ง๊ณ ์ถ์์ต๋๋ค.
์ฌ์ฉ์๊ฐ ๋ณด๊ฑฐ๋, ์ข์ํ๊ฑฐ๋, ์น๊ตฌ๊ฐ ์ข์ํ ์ฑ ์ ๊ธฐ๋ฐ์ผ๋ก ์ถ์ฒ ์ฑ ๋ชฉ๋ก์ ์์ฑํ๋ ๊ฒ๊ณผ ๊ฐ์ ์์ ์ ์ํํ ๋ ์ด ๊ธฐ๋ฅ์ด ์ ์ฉํ๋ค๋ ๊ฒ์ ์์์ต๋๋ค. ๊ทธ๋ฐ ๋ค์ ๊ฐ๋ฅํ ๊ถ์ฅ ์ฌํญ์ ๊ณ ์ ํ ๋ชฉ๋ก์ ๋ณด์ฌ์ค๋๋ค.
function distinct(items, prop) {
var unique = [];
var distinctItems = [];
_.each(items, function(item) {
if (unique[item[prop]] === undefined) {
distinctItems.push(item);
}
unique[item[prop]] = 0;
});
return distinctItems;
}
// likedBooks + viewedBooks + friendLikedBooks + friendViewedBooks
var books = [
{ name: 'Holes', id: 1 },
{ name: 'Treasure Island', id: 2 },
{ name: 'Holes', id: 2 }
];
var uniqueBooks = distinct(books, 'id');
console.log(uniqueBooks);
/**
var uniqueBooks = [
{ name: 'Holes', id: 1 },
{ name: 'Treasure Island', id: 2 }
];
*/
์ข ๋ ์ ์ ํ ํ๋ณด๋ฅผ ํ๊ณ ์ถ์ง๋ง ์ฌ๋๋ค์ด ๋จผ์ ์ด๋ป๊ฒ ์๊ฐํ๋์ง ๋ณด๊ณ ์ถ์์ต๋๋ค.
์์ฑ ์ด๋ฆ ์๊ธฐ๋ฅผ ์ฌ์ฉํ ์๋ ์์ง๋ง ๋ค์์ ์ฌ์ฉํ์ฌ ์ด๋ฅผ ์ํํ ์ ์์ต๋๋ค.
_.uniq(books, function(book) { return book.id; })
Ty @bradunbar ๋ฌธ์์์ ๊ทธ๋ ๊ฒ ํ ์ ์๋ค๊ณ ์๊ฐํ์ง ์์์ต๋๋ค. ๋ ๋ฒ์งธ ์๋ก์ ์ ๋ง ๋์์ด ๋ ๊ฒ์
๋๋ค.
http://underscorejs.org/#uniq
์๋ก์ด _.property
๋ฉ์๋๋ ์ด ์ฌ์ฉ ์ฌ๋ก๋ฅผ ์์ฃผ ํ๋ฅญํ๊ฒ ํด๊ฒฐํ ์ ์์ด์ผ ํฉ๋๋ค.
๊ฐ์ฅ ์ ์ฉํ ๋๊ธ
์์ฑ ์ด๋ฆ ์๊ธฐ๋ฅผ ์ฌ์ฉํ ์๋ ์์ง๋ง ๋ค์์ ์ฌ์ฉํ์ฌ ์ด๋ฅผ ์ํํ ์ ์์ต๋๋ค.