检查数组中的对值

时间:2018-12-18 13:20:29

标签: javascript arrays loops for-loop

在这里我想问一下如何检查数组中的数据(如果下一个索引的值/数据不相同),将其压入新数组中,

这是示例:

function check(arr){
  let text = "";
  let newArr = [];
for(let i = 0 ; i < arr.length-1 ; i++){
  if(arr[i] !== arr[i+1]){
    text = arr[i] + ' and ' + arr[i+1];
    newArr.push(text)
  }
}
return newArr
};

console.log(check([ 'A', 'A', 'M', 'Y', 'I', 'W', 'W', 'M', 'R', 'Y' ])) 
// output "A and M", "A and Y", "I and W", "W and M",  "R and Y"]
console.log(check([ 'a', 'b', 'j', 'j', 'i', 't' ]))

我的结果不是我想要的,它重复了我已经推送的数据。在newArr

我想要这样的ouput

["A and M", "A and Y", "I and W", "W and M",  "R and Y"]

因为每个数组的首字母都不相同

我希望这个问题有意义

1 个答案:

答案 0 :(得分:2)

您可以执行以下操作:

function check(arr) {
  let text = "";
  let newArr = [];
  for (let i = 0, next = 0; i < arr.length; i++) {
    if (next == 2) {
      next = 0;
      i += 2;
    }
    if (arr[i + 1] !== undefined) {
      if (arr[i + 2] !== undefined) {
        text = arr[i] + ' and ' + arr[i + 2];
      } else {
        text = arr[i] + ' and ' + arr[i + 1];
      }
      newArr.push(text)
    }
    next += 1;
  }
  return newArr
};

console.log(check(['A', 'A', 'M', 'Y', 'I', 'W', 'W', 'M', 'R', 'Y']))
console.log(check(['a', 'b', 'j', 'j', 'i', 't']))