_.union()
_.union() เป็นเมธอดของไลบรารี underscore.js ใช้รับอาร์เรย์หลายตัวและคืนค่าอาร์เรย์ใหม่ที่มีเฉพาะค่าที่ไม่ซ้ำกัน (union) จากทุกอาร์เรย์ที่ส่งเข้าไป
ไวยากรณ์
_.union(array1, array2, ...);
ตัวอย่าง
<html> <body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
<script type="text/javascript">
document.write(_.union([1, 2, 9, 40], [1, 20, 3, 2], [9, 2]));
</script> </body> </html>
ผลลัพธ์
1,2,9,40,20,3
รองรับทุกประเภทข้อมูล รวมถึงค่า falsy เช่น empty string, null, undefined
ตัวอย่างกับค่าประเภทต่างๆ
<html> <body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
<script type="text/javascript">
document.write(_.union(["hello",2, "hi", 1, ""], ['the', undefined], ['', null], ["*", ""]));
</script> </body> </html>
ผลลัพธ์
hello,2,hi,1,,the,,,*