Find the longest character in the array
// Create an array
var stringArr = ['hi'.'i'.'am'.'hahaha'.'hehe']
Copy the code
Method 1: Go through the number group
// Record the longest character length and index object, initialization length and index is 0
var longest = {
len: 0.in: 0
};
stringArr.forEach((item, index) = > {
if (item.length > longest.len) {
longest.len = item.length
longest.in = index
}
})
console.log('len:', longest.len)
console.log('str:', stringArr[longest.in])
Copy the code
Method 2: Array sort () method
stringArr.sort((s1, s2) = > {
return s1.length - s2.length;
})
let longeststr = stringArr.pop();
console.log('str:', longeststr)
Copy the code
Method 3: Array reduce() method
var strr = stringArr.reduce((pre, cur) = > {
return cur.length > pre.length ? cur : pre
})
console.log(strr, strr.length)
Copy the code
Array to heavy
Method 1: loop through
const unique = []
function uniqueFunc(arr) {
for (const i = 0; i<arr.length; i++) {if(unique.indexOf(arr[i] === - 1) { // If the current loop element does not exist in the target array, the current element is put into the target array
unique.push(arr[i])
}
}
}
Copy the code
Method 2: array subscript judgment
function uniqueFunc(arr) {
const unq = []
for(const i=0; i<arr.length; i++) {if(arr[i].indexOf(arr[i] === i)) { // If the index of the current loop element in the array is equal to I of the current loop, the element is placed in the target array
unq.push(arr[i])
}
}
}
Copy the code
Method three: sorting adjacent removal
function uniqueFunc(arr) {
arr.sort((a,b) = >(a - b)) sort the array firstconst unique = [arr[0]]
for(const i=0=1; i<arr.length; i++){if(arr[i] ! == arr[i -1]) {
unique.push(arr[i])
}
}
return unique
}
Copy the code
Es6 set()
Set () is a new data structure added to ES6 called a collection, similar to an array in that its members are uniqueconst unique = new Set(arr) // This is a similar array that needs to be converted to true
const res = [...unique] // Convert to a true array
Copy the code