- The simplest idea is to first create a new array as a container, traverse the original array, determine if each item exists in the new array, push the item to the new array if it does not exist, or omit it if it exists.
var arr = [1, 2, 3, 2, 4, 1]; var newArr = []; for (var i = 0; i < arr.length; i++) { if (Newarr.indexof (arr[i]) = = = 1) { NEWARR . push (Arr[i]); // [1, 2, 3, 4]
- Modify the original array directly. Traversing the original array, using IndexOf to judge each item, if the return value is not equal to the index value of itself, the same value is already present (because IndexOf returns the index value of the first match), and the item is removed using splice ().
var arr = [1, 2, 3, 2, 4, 1]; for (var i = 0; i < arr.length; I++ if (Arr.indexof (arr[i])!== i) {Arr.splice (i, 1 // [1, 2, 3, 4]
- Using the object's property name cannot repeat this attribute, create an object, add the values in the array to the object's properties, and then use Object.keys () to get an array containing all the property names. Note, however, that the property names of the objects are in string form, so in this case they are also reversed to numbers.
var arr = [1, 2, 3, 2, 4, 1]; var obj = {}; var res = [];arr.every (n = obj[n] = 1); // add each item as an object's property, the repeating property is not added again, but the value of the existing property is modified res = Object.keys (obj). Map (n = +n); // get an array containing string property names and convert each item to a number console.log (res); // [1, 2, 3, 4]
- First sort the array, then loop, if the two adjacent items are the same, delete one, i--, and then continue the comparison.
var arr = [1, 2, 3, 2, 4, 1 for (var i = 0; i < arr.length; I++ if (arr[i] = = = Arr[i+1 1--; }}console.log (arr); // [1, 2, 3, 4]
- The shortest way to use the new Set ([...]).
var arr = [1, 2, 3, 2, 4, 1]; var New Set (arr);
// [1, 2, 3, 4];
5 ways to implement array de-weight