在现有数组中分组并计算数据以创建新的重组数组

时间:2018-04-19 08:08:23

标签: javascript

我有一个数组如下:

import numpy as np
import cv2

im = cv2.imread('test.jpg')
imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
imgray = cv2.medianBlur(imgray, ksize=7)

ret, thresh = cv2.threshold(imgray, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
_, contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

print ("number of countours detected before filtering %d -> "%len(contours))
new = np.zeros(imgray.shape)

new = cv2.drawContours(im,contours,len(contours)-1,(0,0,255),18)

cv2.namedWindow('Display',cv2.WINDOW_NORMAL)
cv2.imshow('Display',new)
cv2.waitKey()

mask = np.zeros(imgray.shape,np.uint8)
cv2.drawContours(mask,[contours[len(contours)-1]],0,255,-1)
pixelpoints = cv2.findNonZero(mask)
cv2.imwrite("masked_image.jpg",mask)

print(len(pixelpoints))
print("type of pixelpoints is %s" %type(pixelpoints))

我正在尝试创建一个由顾问对客户进行分组的数组,并将consultantID作为属性包括如下:

[
{customer: bryan, id: 123, consultant: Dave, consultantID: 400}
{customer: sharon, id: 124, consultant: Dave, consultantID: 400}
{customer: bobby, id: 125, consultant: Simon, consultantID: 401} 
{customer: chris, id: 126, consultant: Dave, consultantID: 400} 
{customer: sanji, id: 127, consultant: Lars, consultantID: 402}
]

以前在项目中,我一直使用groupby addon来整理信息。这样可以很好地计算每位顾问的客户数,但我不能同时使用名称和ID。

我尝试在阵列上使用类似于以下内容的forEach:

[
{consultant: Dave, count: 3, consultantID: 400}
{consultant: Simon, count: 1, consultantID: 401}
{consultant: Lars, count: 1, consultantID: 402}
]

但这会给每条记录带来回报(显然),我不确定如何构建这种功能。我怀疑我可能需要嵌套多个循环,但我不熟悉这个过程,因为我是Javascrtip的新手

感谢任何帮助

编辑:这是作为Ember Computed属性的Denys答案的实现。

function(){
  let newArray = []
    let patientCount = 0;
    this.get('customerArray').forEach(function(x) {
      let name = x.consultant_name
      let id = x.consultant_id
      let newData = {
        consultantName: name,
        consultantID: id,
      }
      patientCount++
      newArray.push(newData)
    })
    return newArray
}

3 个答案:

答案 0 :(得分:1)

这一系列问题的基本方法通常是使用一个地图(或一个对象作为地图),其关键字是您要分组的ID,并将您的数组reduce用于该地图。< / p>

let src = [
{customer: "bryan", id: 123, consultant: "Dave", consultantID: 400},
{customer: "sharon", id: 124, consultant: "Dave", consultantID: 400},
{customer: "bobby", id: 125, consultant: "Simon", consultantID: 401}, 
{customer: "chris", id: 126, consultant: "Dave", consultantID: 400},
{customer: "sanji", id: 127, consultant: "Lars", consultantID: 402}
];

let grouped = Object.values(src.reduce((s, e)=>{
     let c = s[e.consultantID];
     if (!c) {
           c = s[e.consultantID] = {
              consultant: e.consultant,
              consultantId: e.consultantID,
              count: 0
           };
     }
     c.count++;
     return s;
}, {}));

console.log("result:", grouped);

答案 1 :(得分:1)

您可以使用数组,键和所需属性作为参数的函数,并使用Map作为同一个想要的属性的集合。

function groupBy(array, key, properties) {
    var map = new Map;

    array.forEach(o => {
        if (map.has(o[key])) {
            map.get(o[key]).count++;
            return;
        }
        map.set(o[key], Object.assign(...properties.map(k => ({ [k]: o[k] })), { count: 1 }));
    });
    return Array.from(map.values());
}

var data = [{ customer: 'bryan', id: 123, consultant: 'Dave', consultantID: 400 }, { customer: 'sharon', id: 124, consultant: 'Dave', consultantID: 400 }, { customer: 'bobby', id: 125, consultant: 'Simon', consultantID: 401 }, { customer: 'chris', id: 126, consultant: 'Dave', consultantID: 400 }, { customer: 'sanji', id: 127, consultant: 'Lars', consultantID: 402 }];

console.log(groupBy(data, 'consultantID', ['consultant', 'consultantID']));
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:1)

ES6

您还可以使用reduce()some()filter()spread syntax来获取所需的结果。

<强>样本

const arr=[
{customer: 'bryan', id: 123, consultant: 'Dave', consultantID: 400},
{customer: 'sharon', id: 124, consultant: 'Dave', consultantID: 400},
{customer: 'bobby', id: 125, consultant: 'Simon', consultantID: 401} ,
{customer: 'chris', id: 126, consultant: 'Dave', consultantID: 400} ,
{customer: 'sanji', id: 127, consultant: 'Lars', consultantID: 402}
]

let result = arr.reduce((r, {consultantID,consultant}) => {
    if (!r.some(o => o.consultantID == consultantID)) {
        r.push({consultantID,consultant,count: arr.filter(v => v.consultantID == consultantID).length});
    }
    return r;
}, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }