Set
let arr = […new Set(array)]
splice
Splice does not perform very well when manipulating elements. The index changes when the current item is deleted
for (let i = 0; i < array.length-1; i++) { let currentItem = array[i], sliceArr = array.slice(i+1); If (slicear.indexof (currentItem) > -1){array.splice(I +1, 1)Copy the code
Improved method: first change duplicate elements to NULL and finally unified processing
for (let i = 0; i < array.length-1; i++) { let currentItem = array[i], sliceArr = array.slice(i+1); if(sliceArr.indexOf(currentItem) > -1){ array[i+1] = null } } array = array.filter(item => item! ==null)Copy the code
Assigns a new array
let newArray = [...array]
for (let i = 0; i < array.length; i++) {
let currentItem = array[i],
sliceArr = array.slice(i+1);
if(sliceArr.indexOf(currentItem) > -1){
newArray.splice(i+1, 1)
}
}
console.log(newArray);
Copy the code
Create a new empty array
let newArray = []
for (let i = 0; i < array.length; i++) {
let currentItem = array[i],
sliceArr = array.slice(i+1);
if(sliceArr.indexOf(currentItem) === -1){
newArray.push(currentItem)
}
}
Copy the code
I’m going to fill in the last term
for (let i = 0; i < array.length-1; i++) {
let currentItem = array[i],
sliceArr = array.slice(i+1);
if(sliceArr.indexOf(currentItem) > -1){
array[i] = array[array.length - 1]
array.length --
i --
}
}
Copy the code
Value pairs in the object
Take each item in the array and store it in the new container and if it has already been stored, eliminate the current item
let obj = {} for (let i = 0; i < array.length; i++) { const item = array[i]; if(typeof obj[item] ! == 'undefined'){ array[i] = array[array.length - 1] array.length -- i-- continue } obj[item] = item }Copy the code
Sort first, then compare adjacent (based on regex)
Array. Sort (a, b) = > (a - b) / / ascending array = array. Join (' @ ') + '@' let reg = / (\ d + @) \ 1 * / g, arr = [] array. Replace (reg, (val, group) => { console.log(val,'------',group); / * 1 print information @ @ 2 -- -- -- -- -- - 1 @ @ - 2-2 3 @ @ -- -- -- -- -- - 3 @ 4 @ @ 4 -- -- -- -- -- - 4 @ @ 5 -- -- -- -- -- - 5 @ 6 @ @ -- -- -- -- -- - 6 @ @ -- -- -- -- -- - 7 July 8 @ @ @ -- -- -- -- -- - 8 @ 9 September 9 @ @ -- -- -- -- -- - * / arr. Push (Number (group. Slice (0, group. The length - 1))) / / or arr. Push (parseFloat (group))})Copy the code