每天一道JavaScript算法题(1)

Implement the function unique_in_order which takes as argument a sequence and returns a list of items without any elements with the same value next to each other and preserving the original order of elements.

翻译:实现一个unique_in_order函数,该函数接受一个序列作为参数,返回一个列表,列表中的每一项与其他项的值都不相同,并且元素的原始顺序保持不变。

For example:

uniqueInOrder('AAAABBBCCDAABBB') == ['A', 'B', 'C', 'D', 'A', 'B']
uniqueInOrder('ABBCcAD')         == ['A', 'B', 'C', 'c', 'A', 'D']
uniqueInOrder([1,2,2,3,3])       == [1,2,3]

Solution:

var uniqueInOrder=function(iterable){
  //your code here - remember iterable can be a string or an array
  let result = [];
  let last;
  for (let i = 0; i < iterable.length; i++) {
    if (iterable[i] !== last){
      result.push(last = iterable[i]);
    }
  }
  return result;
}

首先for循环

  var a = [1,2,3,4,5];
  for(let i = 0; i < a.length; i++) {
    console.log(a[i]);
  } // 1 2 3 4 5
  var b = '12345';
  for(let i = 0; i < b.length; i++) {
    console.log(b[i]);
  } // 1 2 3 4 5

数组方法push
push()Array的末尾添加若干元素
例如:

  var a = [1,2,3,4,5];
  var c;
  a.push(c = 1);
  console.log(a); // [1, 2, 3, 4, 5, 1]

明白了这两个方法这道题也就迎刃而解了。无非就是判断这个值存不存在,如果不存就push到数组中。
还有没有其他的解决办法呢?
自己思考一下吧~
tips: 试着用js的高阶函数filter实现吧。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容