배열에서 고유 한 값 목록을 얻으려면 어떻게해야합니까? 항상 두 번째 배열을 사용해야합니까, 아니면 JavaScript의 java 해시 맵과 비슷한 것이 있습니까?
JavaScript 와 jQuery 만 사용하려고합니다 . 추가 라이브러리를 사용할 수 없습니다.
답변
@Rocket의 답변에 대한 의견에서 계속 진행 했으므로 라이브러리를 사용하지 않는 예를 제공 할 수도 있습니다. 이 두 개의 새로운 프로토 타입 기능을 필요로 contains
하고unique
Array.prototype.contains = function(v) {
for (var i = 0; i < this.length; i++) {
if (this[i] === v) return true;
}
return false;
};
Array.prototype.unique = function() {
var arr = [];
for (var i = 0; i < this.length; i++) {
if (!arr.contains(this[i])) {
arr.push(this[i]);
}
}
return arr;
}
var duplicates = [1, 3, 4, 2, 1, 2, 3, 8];
var uniques = duplicates.unique(); // result = [1,3,4,2,8]
console.log(uniques);
신뢰성 contains
을 높이기 위해 MDN indexOf
심으로 교체 하고 각 요소 indexOf
가 -1과 같은지 확인할 수 있습니다.
답변
또는 단일 라이너 (간단하고 기능적인)를 찾는 사람들에게 현재 브라우저와 호환되는 :
let a = ["1", "1", "2", "3", "3", "1"];
let unique = a.filter((item, i, ar) => ar.indexOf(item) === i);
console.log(unique);
18-04-2017 업데이트
‘Array.prototype.includes’가 최신 버전의 기본 브라우저에서 광범위하게 지원되는 것처럼 보입니다 ( 호환성 ).
29-07-2015 업데이트 :
브라우저가 표준화 된 ‘Array.prototype.includes’메소드를 지원할 계획이 있지만이 질문에 직접 대답하지는 않습니다. 종종 관련이 있습니다.
용법:
["1", "1", "2", "3", "3", "1"].includes("2"); // true
폴리 필 ( 브라우저 지원 , mozilla 소스 ) :
// https://tc39.github.io/ecma262/#sec-array.prototype.includes
if (!Array.prototype.includes) {
Object.defineProperty(Array.prototype, 'includes', {
value: function(searchElement, fromIndex) {
// 1. Let O be ? ToObject(this value).
if (this == null) {
throw new TypeError('"this" is null or not defined');
}
var o = Object(this);
// 2. Let len be ? ToLength(? Get(O, "length")).
var len = o.length >>> 0;
// 3. If len is 0, return false.
if (len === 0) {
return false;
}
// 4. Let n be ? ToInteger(fromIndex).
// (If fromIndex is undefined, this step produces the value 0.)
var n = fromIndex | 0;
// 5. If n ≥ 0, then
// a. Let k be n.
// 6. Else n < 0,
// a. Let k be len + n.
// b. If k < 0, let k be 0.
var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
// 7. Repeat, while k < len
while (k < len) {
// a. Let elementK be the result of ? Get(O, ! ToString(k)).
// b. If SameValueZero(searchElement, elementK) is true, return true.
// c. Increase k by 1.
// NOTE: === provides the correct "SameValueZero" comparison needed here.
if (o[k] === searchElement) {
return true;
}
k++;
}
// 8. Return false
return false;
}
});
}
답변
여기에 포함되지 않은 ES6에 대한 훨씬 깨끗한 솔루션이 있습니다. Set 과 spread 연산자를 사용합니다 ....
var a = [1, 1, 2];
[... new Set(a)]
어떤 반환 [1, 2]
답변
하나의 라이너, 순수한 JavaScript
ES6 구문 사용
list = list.filter((x, i, a) => a.indexOf(x) === i)
x --> item in array
i --> index of item
a --> array reference, (in this case "list")
ES5 구문 사용
list = list.filter(function (x, i, a) {
return a.indexOf(x) === i;
});
브라우저 호환성 : IE9 +
답변
EcmaScript 2016을 사용하면 간단히 이렇게 할 수 있습니다.
var arr = ["a", "a", "b"];
var uniqueArray = Array.from(new Set(arr)); // Unique Array ['a', 'b'];
집합은 항상 고유하며 사용 Array.from()
하면 집합을 배열로 변환 할 수 있습니다. 참고로 설명서를 살펴보십시오.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects /세트
답변
이제 ES6에서 새롭게 도입 된 ES6 기능을 사용할 수 있습니다
let items = [1,1,1,1,3,4,5,2,23,1,4,4,4,2,2,2]
let uniqueItems = Array.from(new Set(items))
또는 iterables의 Array 확산 구문
let items = [1,1,1,1,3,4,5,2,23,1,4,4,4,2,2,2];
let uniqueItems = [...new Set(items)];
고유 한 결과를 반환합니다.
[1, 3, 4, 5, 2, 23]
답변
원래 배열을 그대로 두려면
첫 번째의 uniqe 요소를 포함하려면 두 번째 배열이 필요합니다.
대부분의 브라우저에는 Array.prototype.filter
다음 이 있습니다 .
var unique= array1.filter(function(itm, i){
return array1.indexOf(itm)== i;
// returns true for only the first instance of itm
});
//if you need a 'shim':
Array.prototype.filter= Array.prototype.filter || function(fun, scope){
var T= this, A= [], i= 0, itm, L= T.length;
if(typeof fun== 'function'){
while(i<L){
if(i in T){
itm= T[i];
if(fun.call(scope, itm, i, T)) A[A.length]= itm;
}
++i;
}
}
return A;
}
Array.prototype.indexOf= Array.prototype.indexOf || function(what, i){
if(!i || typeof i!= 'number') i= 0;
var L= this.length;
while(i<L){
if(this[i]=== what) return i;
++i;
}
return -1;
}
