【问题标题】:Javascript: Replace same consecutive elements of an array into one item that shows their count inJavascript:将数组的相同连续元素替换为一个显示其计数的项目
【发布时间】:2022-02-05 11:05:58
【问题描述】:

我有一个这样的数组

const array = [1, 3, x, x, 4, x, x, x, 9, x, x, x, x, 7]

我想将所有具有x 值的连续元素转换为一个元素,显示它们在数字之间的计数,例如 :

const newArray = [1, 3, '2x', 4, '3x', 9, '4x', 7]

例如,数组中的 3 个连续的 x [x, x, x] 应该变成一个 ['3x'],而数字应该保持不变。

【问题讨论】:

  • 欢迎来到 Stack Overflow!如果您还没有,请使用tour(您将获得徽章!)并通读help center,尤其是How do I ask a good question? 您最好的选择是进行研究,search 以获取有关 SO 的相关主题和其他地方,试一试。 如果您在进行更多研究和搜索后遇到困难并且无法摆脱困境,请发布minimal reproducible example 展示您的尝试并具体说明您遇到的问题。人们会很乐意提供帮助。

标签: javascript arrays


【解决方案1】:

也许有更好的解决方案来实现这一目标。 当然,有! 但是这里有一个使用for 循环的解决方案。如果元素为x,则检查每次迭代,将x 的值增加1。如果当前元素不是x,则将x变量重置为0

样本结果:

const array = [1, 3, 'x', 'x', 4, 'x', 'x', 'x', 9, 'x', 'x', 'x', 'x', 7];

let x = 0;
let result = [];

for (let i = 0; i < array.length; i++) {
  if (array[i] === 'x') {
    x++;
    if (array[i + 1] === 'x') continue;
    result.push(`${x}x`);
    continue;
  }
  x = 0;
  result.push(array[i]);
}

console.log(result);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration

【讨论】:

    【解决方案2】:

    const array = [1, 3, 'x', 'x', 4, 'x', 'x', 'x', 9, 'x', 'x', 'x', 'x', 7]
    
    const newArray = array.map(item => `${item}`).reduce((acc, curr)=>{
        if(curr !== 'x') return [...acc, curr];
        
        const previous = acc.pop();
        if(!previous || !previous.includes('x')) return [...acc, previous, '1x'];
    
        const xCounter = 1 + parseInt(previous.match(/\d+/)[0]);
        return [...acc, `${xCounter}x`];
        
    },[])
    
    console.log(newArray)

    【讨论】:

      【解决方案3】:

      最简单的方法就是迭代所有元素:

      // Your array
      const array = [
        1,
        3,
        "x",
        "x",
        4,
        "x",
        "x",
        "x",
        9,
        "x",
        "x",
        "x",
        "x",
        7
      ];
      
      // Create new array
      const newArr = [];
      
      // Set internal value repeat counter
      let cn = 1;
      
      // Iterate array
      for(let i = 0; i < array.length; i++) {
        // Set trigger
        let trig = 1;
        
        // If next param exist and it is equals current
        if(array[i+1] && array[i+1] === array[i]) {
          // Increase counter
          cn++;
          // Set trigger to false
          trig = 0;
        }
        
        // If trigger is true
        if(trig) {
          // If internal counter greater then 1
          // push previous value and its counter
          if(cn > 1) {
            newArr.push(`${cn}${array[i-1]}`);
            // Reset counter
            cn = 1;
          }
          
          // Else just push current value
          else newArr.push(array[i]);
        }
      }
      
      // Test
      console.log(newArr);

      然后你可以尝试用更高级的东西来缩小代码:

      // Your array
      const arr = [1,3,"x","x",4,"x","x","x",9,"x","x","x","x",7];
      
      // Use flatMap
      let cn = 1;
      const res = arr.flatMap((e, i, a) => {
        return a[i+1] && a[i+1] == e ? (cn++) && [] :
        cn > 1 ? (()=>{const t = cn; cn = 1; return t+''+a[i-1]})() : e;
      });
      
      // Result
      console.log(res);

      【讨论】:

        猜你喜欢
        • 2019-05-05
        • 1970-01-01
        • 1970-01-01
        • 2013-11-08
        • 2020-05-28
        • 2013-05-28
        • 1970-01-01
        • 2020-03-19
        • 2017-03-19
        相关资源
        最近更新 更多