【问题标题】:Remove items in array if they are next to each other and get duplicate count如果它们彼此相邻,则删除数组中的项目并获得重复计数
【发布时间】:2020-08-14 20:18:30
【问题描述】:

我正在尝试制作一个类似于浏览器中的控制台,但卡在显示重复消息上

假设我得到了这个数组:

const array = [
    {
        output: "testing",
    },
    {
        output: "testing",
    },
    {
        output: "hello",
    },
    {
        output: "world",
    },
    {
        output: "world",
    },
    {
        output: "testing",
    },
]

所需的输出如下所示:

(2)testing    
hello    
(2)world    
testing

如果重复消息彼此相邻,我如何删除它们并添加一个计数器来显示中有多少重复消息。输出应该是这样的

const newArray = [
    {
        output: "testing",
        count: 2
    },
    {
        output: "hello",
        count: 1
    },
    {
        output: "world",
        count: 2
    },

    {
        output: "testing",
        count: 1
    },
]

我认为可能是这样的

const array = [{
    output: "testing",
  },
  {
    output: "testing",
  },
  {
    output: "hello",
  },
  {
    output: "world",
  },
  {
    output: "world",
  },
  {
    output: "testing",
  },
]
let newArray = [];

for (let i = 0; i < array.length; i++) {
  if (newArray.length.length > 1 && array[i].output == newArray[newArray.length - 1].output) {
    newArray[newArray.length - 1].counter += 1
  } else {
    newArray.push({
      output: array[i].output,
      counter: 0
    })
  }

}
console.log(newArray)

【问题讨论】:

  • 你尝试了什么?
  • @Mitya 我的更新不好,无法解决这个简单的问题有点沮丧,呵呵

标签: javascript arrays


【解决方案1】:

更新:现在它将彼此靠近的条目分组

const array = [
    { output: "testing" },
    { output: "testing" },
    { output: "hello" },
    { output: "world" },
    { output: "world" },
    { output: "testing" }
];

// Result objects
let subRes = false;
const res = [];

// Loop
for(let i = 0; i < array.length; i++) {
  // Create count obj
  if(!subRes) subRes = {
    output: array[i].output,
    count: 1
  }
  // If next is the same
  if(array[i+1] && array[i+1].output === array[i].output) {
    subRes.count++;
  } else {
    res.push(subRes);
    subRes = false;
  }
}

// Log
console.log(res);

【讨论】:

  • 这不考虑项目是否彼此相邻
  • 现在检查一下,这是你想要做的吗?
【解决方案2】:

过滤数组然后打印

以下示例

var array = [
    {
        output: "testing",
    },
    {
        output: "testing",
    },
    {
        output: "hello",
    },
    {
        output: "world",
    },
    {
        output: "world",
    },
    {
        output: "testing",
    },
]

// You can reduce to reduce the array in to single object
data = array.reduce((acc, val) => {  
  if(val.output === acc.last_value){
    acc.result[acc.result.length - 1].count += 1;
  } else {
    acc.result.push({...val, count: 1})
  }
  
  acc.last_value = val.output;
  return acc;
}, {result: [], last_value: null});

console.log(data.result);

【讨论】:

  • 我不想得到唯一的项目,如果它们在数组中的相似项目旁边,我需要获取相同项目的计数
【解决方案3】:

您可以使用reducer 来管理它并更轻松地重复使用它。

版本 1

const array = [...]

const reduceCount = (acc, obj) => {
  const key = obj["output"];
  // check if we already store the key
  if(!(key in acc)){
    //the key is not register yet, so we create a counter state
    acc[key] = {count: 0};
  }

  //increment the key state counter
  acc[key]['count'] += 1
  
  return acc;
}

// Reduce the array to get state of each key
const dictCount = array.reduce(reduceCount, {});

console.log(dictCount) // { testing: { count: 3 }, hello: { count: 1 }, world: { count: 2 } }

const newArray = Object.keys(dictCount).map(key => ({
  output: key, 
  count: dictCount[key]['count']
}));

console.log(newArray) 

/** output
[
  { output: 'testing', count: 3 },
  { output: 'hello', count: 1 },
  { output: 'world', count: 2 }
]
 */

版本 2:更可重用的方式:

const array = [...]

const reduceCount = target => (acc, obj) => {
  const key = obj[target];
  // check if we already store the key
  if(!(key in acc)){
    //the key is not register yet, so we create a counter state
    acc[key] = {count: 0};
  }

  //increment the key state counter
  acc[key]['count'] += 1
  
  return acc;
}

const counterState = target => arr => arr.reduce(reduceCount(target), {});
const counterStateOutput = counterState('output'); //specialize the function

// transform state to array
const stateToArray = state =>  Object.keys(state).map(key => ({
  key,
  count: state[key]["count"]
}));

console.log(stateToArray(counterStateOutput(array))) 
//or
console.log(stateToArray(counterState('output')(array))) 

/** output
[
  { key: 'testing', count: 3 },
  { key: 'hello', count: 1 },
  { key: 'world', count: 2 }
]
 */

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-18
    相关资源
    最近更新 更多