JavaScript循环数组:比较前一个和下一个项。

huangapple go评论69阅读模式
英文:

JavaScript loop array: compare previous and next item

问题

循环数组并比较前一项和后一项。

我的数组:

const array = [{id: 1,name: 'A'},{id: 2,name: 'B'},{id: 3,name: 'B'},{id: 4,name: 'B'},{id: 5,name: 'C'},{id: 6,name: 'D'},{id: 7,name: 'E'},{id: 8,name: 'E'},{id: 9,name: 'E'}]


我的代码:

let result = []
array.forEach(function(item, index) {
if (index > 0) {
if (array[index].name == array[index - 1].name) {
result.push(array[index - 1].name)
}
}
});

console.log('result :', result); // 我得到的结果: [ 'B', 'B', 'E', 'E' ]


但我想要这个结果:

let result = [ 'B', 'B', 'B', 'E', 'E', 'E' ]

英文:

Loop array and compare the previous item and the next item.

My array:

const array = [{id: 1,name: 'A'},{id: 2,name: 'B'},{id: 3,name: 'B'},{id: 4,name: 'B'},{id: 5,name: 'C'},{id: 6,name: 'D'},{id: 7,name: 'E'},{id: 8,name: 'E'},{id: 9,name: 'E'}]

My code:

let result = []
array.forEach(function(item, index) {
    if (index > 0) {
        if (array[index].name == array[index - 1].name) {
            result.push(array[index - 1].name)
        }
    }
});

console.log('result :', result); // The result I got: [ 'B', 'B', 'E', 'E' ]

But I want this result:

let result = [ 'B', 'B', 'B', 'E', 'E', 'E' ]

答案1

得分: 1

在这种情况下,reduce 是关键

let result = array.reduce((acc, curr, index) => {
  const previousItem = array[index - 1];
  if (previousItem && curr.name === previousItem.name) {
    acc.push(curr.name);
  }
  return acc;
}, []);

console.log(result); // 输出: [ 'B', 'B', 'B', 'E', 'E', 'E' ]
英文:

In such cases, reduce is the key

 let result = array.reduce((acc, curr, index) => {
 const previousItem = array[index - 1];
 if (previousItem && curr.name === previousItem.name) {
      acc.push(curr.name);
 }
 return acc;
 }, []);

 console.log(result); // Output: [ 'B', 'B', 'B', 'E', 'E', 'E' ]

答案2

得分: 1

你只需要有条件地检查前一个和后一个值。

const array = [{id: 1, name: 'A'}, {id: 2, name: 'B'}, {id: 3, name: 'B'}, {id: 4, name: 'B'}, {id: 5, name: 'C'}, {id: 6, name: 'D'}, {id: 7, name: 'E'}, {id: 8, name: 'E'}, {id: 9, name: 'E'}]
let result = [];

array.forEach(function(item, index) {

    let prev = index - 1; // Previous value
    let next = index + 1; // Next value

    if(index > 0) {
        if((array[prev].name == array[index].name) || (array[index].name == array[next].name)) {
            result.push(array[index].name)
        }
    }
});

console.log('result: ', result);
英文:

You just need to conditionally check the previous and next value.

const array = [{id: 1,name: 'A'}, {id: 2,name: 'B'}, {id: 3,name: 'B'}, {id: 4,name: 'B'}, {id: 5,name: 'C'}, {id: 6,name: 'D'}, {id: 7,name: 'E'}, {id: 8,name: 'E'}, {id: 9,name: 'E'}]
    let result = [];

    array.forEach(function(item, index) {

        let prev = index - 1; // Previous value
        let next = index + 1; // Next value

        if(index > 0) {
            if((array[prev].name == array[index].name) || (array[index].name == array[next].name)) {
                result.push(array[index].name)
            }
        }
    });

    console.log('result: ', result);

答案3

得分: 0

// 使用:

<!-- 开始代码段: js 隐藏: false 控制台: true Babel: false -->

<!-- 语言: lang-js -->

const array = [
  { id: 1, name: 'A' },
  { id: 2, name: 'B' },
  { id: 3, name: 'B' },
  { id: 4, name: 'B' },
  { id: 5, name: 'C' },
  { id: 6, name: 'D' },
  { id: 7, name: 'E' },
  { id: 8, name: 'E' },
  { id: 9, name: 'E' }
];

const result = [];
let prevName = null;
let count = 0;

array.forEach(item => {
  if (item.name === prevName) {
    count++;
  } else {
    if (count > 1) {
      for (let i = 0; i < count; i++) {
        result.push(prevName);
      }
    }
    prevName = item.name;
    count = 1;
  }
});

if (count > 1) {
  for (let i = 0; i < count; i++) {
    result.push(prevName);
  }
}

console.log('result:', result);

<!-- 结束代码段 -->
英文:

Use:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const array = [
{ id: 1, name: &#39;A&#39; },
{ id: 2, name: &#39;B&#39; },
{ id: 3, name: &#39;B&#39; },
{ id: 4, name: &#39;B&#39; },
{ id: 5, name: &#39;C&#39; },
{ id: 6, name: &#39;D&#39; },
{ id: 7, name: &#39;E&#39; },
{ id: 8, name: &#39;E&#39; },
{ id: 9, name: &#39;E&#39; }
];
const result = [];
let prevName = null;
let count = 0;
array.forEach(item =&gt; {
if (item.name === prevName) {
count++;
} else {
if (count &gt; 1) {
for (let i = 0; i &lt; count; i++) {
result.push(prevName);
}
}
prevName = item.name;
count = 1;
}
});
if (count &gt; 1) {
for (let i = 0; i &lt; count; i++) {
result.push(prevName);
}
}
console.log(&#39;result:&#39;, result);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年5月30日 13:09:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76361753.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定