反向数组,让新数组中的元素等于原始数组元素的长度-JavaScript

时间:2019-05-19 03:28:58

标签: javascript arrays reverse string-length

尝试解决this kata on Codewars

我已经能够将数组反转为一个字符串,但是无法将该字符串分配给指定长度的各个元素。我尝试过:

function ultimateReverse (array) {

 let newArray = array.join("").split("");
 let reversedArray = newArray.reverse();
 return reversedArray.join("");

}

console.log(ultimateReverse(["I", "like", "big", "butts", "and", "I", "cannot", "lie!"]));

//!eiltonnacIdnasttubgibekilI

但是我们想要的结果是:

["!", "eilt", "onn", "acIdn", "ast", "t", "ubgibe", "kilI"]

因此,根据原始数组,第一个元素的长度应为1,第二个元素的长度应为4,第三个元素的长度应为3,依此类推...

是否可以将字符串拆分为元素数组,每个元素都有指定的长度?

我想通过执行以下操作从原始数组创建一个数组,该数组的长度由项目组成:

function ultimateReverse (array) {

let elementLengths = [];

let newArray = array.join("").split("");
let reversedArray = newArray.reverse().join("");

for (let i = 0; i < array.length; i++) {
  let element = array[i];
  elementLengths.push(element.length);
}

return reversedArray + " " + elementLengths;

}

console.log(ultimateReverse(["I", "like", "big", "butts", "and", "I", "cannot", "lie!"]));

//!eiltonnacIdnasttubgibekilI 1,4,3,5,3,1,6,4

现在,如果我可以根据原始元素的长度将字符串分成数组中的元素...

2 个答案:

答案 0 :(得分:10)

首先构造完整的反向字符串,例如

!eiltonnacIdnasttubgibekilI

然后,从初始长度的数组(可以预先用.map完成)中,遍历该数组,并从反转的字符串中重复slice的长度,然后推入数组:

function ultimateReverse(array) {
  const lengths = array.map(({ length }) => length);
  let reversedStr = [...array.join("")].reverse().join('');
  const result = [];
  lengths.forEach((length) => {
    result.push(reversedStr.slice(0, length));
    reversedStr = reversedStr.slice(length);
  });
  return result;
}

console.log(ultimateReverse(["I", "like", "big", "butts", "and", "I", "cannot", "lie!"]));

您还可以将初始反向数据保留为splice的数组,而不是重新分配reversedStr

function ultimateReverse(array) {
  const lengths = array.map(({ length }) => length);
  const reversedChars = [...array.join('')].reverse();
  return lengths.map(
    length => reversedChars.splice(0, length).join('')
  );
}

console.log(ultimateReverse(["I", "like", "big", "butts", "and", "I", "cannot", "lie!"]));

答案 1 :(得分:1)

您还可以通过以下方式解决此问题:验证字符串,然后将其映射并使用substr将其“切成碎片”,如下所示:

let reverse = arr => {	
  let i = 0, rData = [...arr.join('')].reverse().join('')
  return arr.map(x => {
    let str = rData.substr(i, x.length)
    i += x.length 
    return str
  })
}

console.log(reverse(["I", "like", "big", "butts", "and", "I", "cannot", "lie!"]))

基本上映射整个原始数组,并为组合后的反向字符串中的每个字符串substr映射,与当前x长度一样多。