正负转换
function invert(array) {
return array.map(item => {
return -item
});
}
var arr = [1, 23, 4, -5, -8]
console.log(invert(arr))
翻转字符串
function solution(str){
return str.split('').reverse().join('')
}
console.log(solution("world"))
数组中某些值相加
指定某些条件的值进行相加
function positiveSum(arr) {
return arr.filter(x => {
x > 0
}).reduce((s, v) => {
s += v
}, 0)
}
var arr = [1, -4, 7, 12]
console.log(positiveSum(arr))
function positiveSum(arr) {
return arr.reduce((a,b)=> a + (b > 0 ? b : 0),0);
}
去除数组中最小与最大值并求和
function sumArray(array) {
return array ? array.sort((a, b) => {
return a - b
}).slice(1, -1).reduce((a, b) => {
return a + b
}, 0) : 0
}
var array = [6, 2, 1, 8, 10]
console.log(sumArray(array))
整体求和在减去一个最大值与一个最小值
function sumArray(array) {
return Array.isArray(array) && array.length > 1
? array.reduce((s, n) => s + n, 0) - Math.min(...array) - Math.max(...array)
: 0
}
对传入的数字进行平方并相加求和
function squareSum(numbers) {
return numbers.map(item=>item*item).reduce((a,b)=>a+b,0)
}
var numbers = [1,2,3]
console.log(squareSum(numbers))
对两个字符串 s1 与 s2 ,要求去除相同的部分,最终返回以 a-z 的顺序的字符串结果
function longest(s1, s2) {
// your code
//组合 去重 排列
let newStr = s1.concat(s2)
let uniqStr = Array.from(new Set(newStr.split('')))
let res = uniqStr.sort().join("")
return res
}
let s1 = "xyaabbbccccdefww"
let s2 = "xxxxyyyyabklmopq"
console.log(longest(s1, s2))
const longest = (s1, s2) => [...new Set(s1+s2)].sort().join('')
function longest(s1, s2) {
return Array.from(new Set(s1 + s2)).sort().join('');
}
对给定数组中按照从小到大的顺序,(取出四位),求前两位进行相加的值
function sumTwoSmallestNumbers(numbers) {
let newNum = numbers.sort((a,b)=>{
return a-b
}).slice(0,4)
return newNum[0] + newNum[1]
}
let numbers = [10, 343445353, 3453445, 3453545353453]
console.log(sumTwoSmallestNumbers(numbers))
function sumTwoSmallestNumbers(numbers) {
var [ a, b ] = numbers.sort((a, b) => a - b)
return a + b
}
求给定数组中的平均值
function find_average(array) {
return array.reduce((a, b) => {
return a + b
}, 0) / array.length
}
let array = [1, 2, 3]
console.log(find_average(array))
解析域名中的字符串
示例中的一些情况 Test.assertEquals(domainName(“http://google.com“), “google”); Test.assertEquals(domainName(“http://google.co.jp“), “google”);
Test.assertEquals(domainName(“www.xakep.ru”), “xakep”);
Test.assertEquals(domainName(“https://youtube.com“), “youtube”);
function domainName(url) {
let res
if (url.includes("http")) {
res = url.split("/")[2]
} else {
res = url
}
if (res.includes("www")) {
return res.split(".")[1]
} else {
return res.split(".")[0]
}
}
let url = "http://github.com/carbonfive/raygun"
domainName(url)
replace 实现
function domainName(url){
url = url.replace("https://", '');
url = url.replace("http://", '');
url = url.replace("www.", '');
return url.split('.')[0];
};
正则表达式
function domainName(url){
return url.replace(/(https?:\/\/)?(www\.)?/, '').split('.')[0]
}
知识储备
- 去重
- 字符串
- 数组
https://blog.csdn.net/weihaifeng163/article/details/87854720