Underscore: (์•„์ด๋””์–ด) ์†์„ฑ๋ณ„ ๊ฐœ์ฒด์˜ ๊ณ ์œ  ๋ฐฐ์—ด

์— ๋งŒ๋“  2013๋…„ 12์›” 10์ผ  ยท  3์ฝ”๋ฉ˜ํŠธ  ยท  ์ถœ์ฒ˜: jashkenas/underscore

๋‚˜๋Š” ์ด๊ฒƒ์„ ๋ฐ‘์ค„์—์„œ ์ด๋ฏธ ๋ณด์ง€ ๋ชปํ–ˆ๊ธฐ ๋•Œ๋ฌธ์— ์ด๊ฒƒ์„ ๊ฑฐ๊ธฐ์— ๋˜์ง€๊ณ  ์‹ถ์—ˆ์Šต๋‹ˆ๋‹ค.

์‚ฌ์šฉ์ž๊ฐ€ ๋ณด๊ฑฐ๋‚˜, ์ข‹์•„ํ•˜๊ฑฐ๋‚˜, ์นœ๊ตฌ๊ฐ€ ์ข‹์•„ํ•œ ์ฑ…์„ ๊ธฐ๋ฐ˜์œผ๋กœ ์ถ”์ฒœ ์ฑ… ๋ชฉ๋ก์„ ์ž‘์„ฑํ•˜๋Š” ๊ฒƒ๊ณผ ๊ฐ™์€ ์ž‘์—…์„ ์ˆ˜ํ–‰ํ•  ๋•Œ ์ด ๊ธฐ๋Šฅ์ด ์œ ์šฉํ•˜๋‹ค๋Š” ๊ฒƒ์„ ์•Œ์•˜์Šต๋‹ˆ๋‹ค. ๊ทธ๋Ÿฐ ๋‹ค์Œ ๊ฐ€๋Šฅํ•œ ๊ถŒ์žฅ ์‚ฌํ•ญ์˜ ๊ณ ์œ ํ•œ ๋ชฉ๋ก์„ ๋ณด์—ฌ์ค๋‹ˆ๋‹ค.

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 }
];
*/

์ข€ ๋” ์ ์ ˆํ•œ ํ™๋ณด๋ฅผ ํ•˜๊ณ  ์‹ถ์ง€๋งŒ ์‚ฌ๋žŒ๋“ค์ด ๋จผ์ € ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜๋Š”์ง€ ๋ณด๊ณ  ์‹ถ์—ˆ์Šต๋‹ˆ๋‹ค.

question

๊ฐ€์žฅ ์œ ์šฉํ•œ ๋Œ“๊ธ€

์†์„ฑ ์ด๋ฆ„ ์†๊ธฐ๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜๋Š” ์—†์ง€๋งŒ ๋‹ค์Œ์„ ์‚ฌ์šฉํ•˜์—ฌ ์ด๋ฅผ ์ˆ˜ํ–‰ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

_.uniq(books, function(book) { return book.id; })

๋ชจ๋“  3 ๋Œ“๊ธ€

์†์„ฑ ์ด๋ฆ„ ์†๊ธฐ๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜๋Š” ์—†์ง€๋งŒ ๋‹ค์Œ์„ ์‚ฌ์šฉํ•˜์—ฌ ์ด๋ฅผ ์ˆ˜ํ–‰ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

_.uniq(books, function(book) { return book.id; })

Ty @bradunbar ๋ฌธ์„œ์—์„œ ๊ทธ๋ ‡๊ฒŒ ํ•  ์ˆ˜ ์žˆ๋‹ค๊ณ  ์ƒ๊ฐํ•˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค. ๋‘ ๋ฒˆ์งธ ์˜ˆ๋กœ์„œ ์ •๋ง ๋„์›€์ด ๋  ๊ฒƒ์ž…๋‹ˆ๋‹ค.
http://underscorejs.org/#uniq

์ƒˆ๋กœ์šด _.property ๋ฉ”์†Œ๋“œ๋Š” ์ด ์‚ฌ์šฉ ์‚ฌ๋ก€๋ฅผ ์•„์ฃผ ํ›Œ๋ฅญํ•˜๊ฒŒ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.

์ด ํŽ˜์ด์ง€๊ฐ€ ๋„์›€์ด ๋˜์—ˆ๋‚˜์š”?
0 / 5 - 0 ๋“ฑ๊ธ‰