# 刷题——Codewars Js问题（延续更新）

#### 1. 将首字母放到背面并加上`ay`

`pigIt('This is my string')`转换成：`pigIt('hisTay siay ymay tringsay')`

• mine

``````function pigIt(str){
var _str = [];
str.split(' ').forEach((_value) => _str.push(_value.slice(1)+_value.slice(0,1)+'ay'));
return _str.join(' ');
}``````
• others

``````function pigIt(str){
return str.replace(/(\w)(\w*)(\s|\$)/g, "\\$2\\$1ay\\$3")
}``````

#### 2. 数组变成字符串而且末了一个用&衔接

`list([{name: 'Bart'},{name: 'Lisa'},{name: 'Maggie'},{name: 'Homer'},{name: 'Marge'}])`转换成：`'Bart, Lisa, Maggie, Homer & Marge'`

• mine

``````function list(names){
if(names.length == 0)return '';
let allname = [];
names.forEach(function(_value){
allname.push(_value.name);
});
let list = allname.join(",");
var _index = list.lastIndexOf(",");
list = list.replace(/,/g,function(a,b){
return b == _index ? ' & ' : ', '
});
return list;
}``````
• others

``````function list(names) {
var xs = names.map(p => p.name)
var x = xs.pop()
return xs.length ? xs.join(", ") + " & " + x : x || ""
}``````

#### 3. 将0移到数组背面且其他值在本来位置不排序

`["a",0,"b",null,"c",0,"d",1,false,1,0,3,[],1,9,{},9,0]`转换成：`["a","b",null,"c","d",1,false,1,3,[],1,9,{},9,0,0,0,0]`

• mine

``````var moveZeros = function (arr) {
let my_arr = arr.concat();
let count = 0;
arr.forEach(function(_value,_index){
if(_value === 0){
my_arr.push(...my_arr.splice(_index-count,1));
count++;
}
});
return my_arr;
}``````
• others

``````var moveZeros = function (arr) {
return arr.filter(function(x) {return x !== 0}).concat(arr.filter(function(x) {return x === 0;}));
}``````

#### 4. 数组内奇数排序，偶数位置稳定

`[5, 3, 2, 8, 1, 4]`转换成：`[1, 3, 2, 8, 5, 4]`

• mine

``````function sortArray(arr) {
var myarr = [],
myindex = [];
arr.map(function(a,b){
if(a%2 !== 0){
console.log(a)
myarr.push(a);
myindex.push(b);
}
});
myarr.sort((a,b) => a - b);
myindex.map(function(a,b){
arr[a] = myarr[b];
});
return arr;
}``````
• others

``````function sortArray(array) {
const odd = array.filter((x) => x % 2).sort((a,b) => a - b);
return array.map((x) => x % 2 ? odd.shift() : x);
}``````

#### 5. 字符串内里的数字排序

`"is2 Thi1s T4est 3a"`转换成：`"Thi1s is2 3a T4est"`

• mine

``````function order(words){
var arr = words.split(' ');
arr.sort(function(a,b){
return /\d/.exec(a)[0] - /\d/.exec(b)[0];
});
return arr.join(' ');
}``````
• others

``````function order(words){
return words.split(' ').sort(function(a, b){
return a.match(/\d/) - b.match(/\d/);
}).join(' ');
}``````

#### 6. 拆分数字并相乘直至个位数

• mine

``````function persistence(num) {
var count = 0;
var Count = function(_num){
var total = 1;
if(_num.toString().length == 1){
return count;
}
total = _num.toString().split('').map((a) => total = total * a).pop();
count++;
return Count(total);
}
return Count(num);
}``````
• others

``````const persistence = num => {
return `\${num}`.length > 1 ? 1 + persistence(`\${num}`.split('').reduce((a, b) => (a * b)))
: 0;
}``````

#### 7. 婚配暗码

• mine

``````function validate(password) {
``````function validate(password) {