最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

logic - Sum of consecutive numbers JavaScript - Stack Overflow

programmeradmin1浏览0评论

Given an array of integers.

For example:

[1,2,2,2,5,7]

I want to output any groups of consecutive identical numbers with their sum.

The output should be:

[1,6,5,7]

Any thoughts on how to do this?

Given an array of integers.

For example:

[1,2,2,2,5,7]

I want to output any groups of consecutive identical numbers with their sum.

The output should be:

[1,6,5,7]

Any thoughts on how to do this?

Share Improve this question edited Feb 20, 2020 at 9:42 Penny Liu 17.5k5 gold badges86 silver badges108 bronze badges asked Jan 26, 2016 at 19:32 ArnoldBArnoldB 1653 silver badges10 bronze badges 2
  • Apply code on stackoverflow./a/9229821/1169519 – Teemu Commented Jan 26, 2016 at 19:36
  • 1 Oh, in meantime you removed your original question! – i-blis Commented Jan 26, 2016 at 20:42
Add a ment  | 

4 Answers 4

Reset to default 3

You can use Array.prototype.reduce() with a temporary object.

var array = [1, 2, 2, 2, 5, 7],
    result = array.reduce(function (r, a) {
        if (r.last === a) {
            r.array[r.array.length - 1] += a;
        } else {
            r.array.push(a);
            r.last = a;
        }
        return r;
    }, { array: [], last: null }).array;

document.write('<pre>' + JSON.stringify(result,0,4) + '</pre>');

I solved it this way.

const sumConsecutives = (s) => {
  let result = [], temp = 0;
  for(let i = 0; i<s.length; i++) {
    if(s[i] === s[i+1]){
      temp += s[i];
    } else if(s[i] !== s[i+1]){
      result.push(temp + s[i]);
      temp = 0;
    }
  }
  return result;
};

If you use lodash and want a functional variant, you could also do:

_.chain([1,2,2,2,5,7]).groupBy(_.identity).map(_.sum).value()

We could solve this using iteration. The code would look something like this

var numbers = [1, 2, 2, 2, 5, 7];
var newNumbers = [];

for (var i = 0; i < numbers.length; i++) {
    numbers = numbers.filter(function(num) {
        return num;
    });

Here we are removing elements that are undefined which will be deleted, so we don't repeat groups.

    var number = numbers[i];
    var nextUnique = numbers.find(function(num) {
        return num != number
    });
    var numbersToFind = numbers.indexOf(nextUnique) - i;

Above, we are searching for the number of numbers in a repeated group.

    if (numbersToFind > 0) {
        var numbersGroup = numbers.slice(i, i + numbersToFind + 1);
        var sumNumbers = numbersGroup.reduce(function(num1, num2) {
            return num1 + num2;
        });
        newNumbers.push(sumNumbers);
        delete numbers[i];
    }

We use the reduce function to sum up the numbers that are identical. We will then delete the original number to prevent duplicates in our newNumbers array.

    else {
        newNumbers.push(numbers[i]);
   }
}

Otherwise, the new number will simply be the number at the index.

alert(newNumbers);

Browser Compatibility

It should be noted that the array.prototype.find function is an experimental technology and is not yet available on Internet Explorer or Opera.

发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>