找到三个顶级标签

时间:2017-12-01 07:40:25

标签: javascript javascript-objects reduce map-function

这将有点冗长,但我正在寻求如何解决/思考的帮助。我想养成批判性地思考这个问题的习惯,但我已经碰壁了。所以任何技巧/提示/建议都表示赞赏。

所以我有一个像这样的多个对象的数组(8个中的一个):

[{
  "_id": "555e4125afb26872ac1cb814",
  "index": 0,
  "guid": "e7bd5b56-43d3-41cb-9742-aee4408a36c2",
  "isActive": false,
  "balance": "$3,868.37",
  "picture": "http://placehold.it/32x32",
  "age": 37,
  "eyeColor": "brown",
  "name": "Adele Mullen",
  "gender": "female",
  "company": "GAPTEC",
  "email": "adelemullen@gaptec.com",
  "phone": "+1 (860) 572-3603",
  "address": "775 Tapscott Street, Mammoth, South Dakota, 9956",
  "about": "Aliqua duis ex id excepteur duis aute non ipsum laborum. Duis exercitation aliquip sint irure consectetur ex enim veniam irure aliquip ipsum dolore cillum sunt. Ea dolor magna cupidatat sint laboris ipsum. Cillum quis nisi laboris officia consequat nulla dolor adipisicing eu. Quis ut nostrud non aliqua.\r\n",
  "registered": "2014-05-12T22:50:11 +05:00",
  "latitude": 30.620088,
  "longitude": -156.753814,
  "tags": ["cupidatat", "do", "irure", "proident", "sit", "nulla", "aute"],
  "friends": [{
    "id": 0,
    "name": "Justice Lara"
  }, {
    "id": 1,
    "name": "Duke Patrick"
  }, {
    "id": 2,
    "name": "Herring Hull"
  }, {
    "id": 3,
    "name": "Johnnie Berg"
  }],
  "greeting": "Hello, Adele Mullen! You have 8 unread messages.",
  "favoriteFruit": "banana"
}

我的目标是创建一个函数,在所有对象的关联标签中查找三个最常见的标签。我的输入和输出将是一个数组,我已经重新创建了三个HOF来处理对象以帮助我完成这个过程:

娱乐减少:

function reduce(array, func, seed) {
var theArray = array;
var previousResult;
var i = 0;
if (seed !== null && seed !== undefined) {
    previousResult = seed;
} else {
    previousResult = array[0];
    theArray = array.slice(1, array.length);
    i =1;
}
each(theArray, function(value, index, collection) {
    previousResult = func(previousResult, value, index + i);
});
return previousResult;

重新制作地图:

function map (collection, func) {
    var newArray = [];
    each(collection, function(value, index, collection) {
       newArray.push(func(value,index, collection)); 
    }); 
    return newArray;

 }

重新创建过滤器

function filter (collection, test) {
    const filtered = [];
    each(collection, function(value, position, collection) {
    if (test(value,position, collection)) 
         filtered.push(value); 
    }); 
    return filtered;
}

我的主要问题是如何推进这个问题,因为我很可能会在链函数反应中使用这些函数。

var topThreeTags = function(customers) {
var topThree = [];
var allTags = [];

_.map(customers, func(customer.tags) {
  topThree.push(customer.tags);
}
_.filter(allTags, function(value, curr, collection) {
      if (test(value.tags === curr[tag])) {
          topThree.push(curr);
      }
  }

};

return topThree;
};

我知道这是不完整的代码,但是我遇到了障碍,我希望能够清楚地知道我在哪里绕道而行以及我需要修复它。

1 个答案:

答案 0 :(得分:2)

尝试这种方法

  • 地图 tag使用次数

var tagMap = {};
arr.forEach( function( item ){
   item.tags.forEach( function( tag ){
      tagMap[ tag ] = ( tagMap[ tag ] || 0 ) + 1;
   })
});

<强> 解释

== 迭代数组中的所有对象 arr

== 对于对象中的每个item迭代其标记

== 对于代码中的每个代码&#39; array 将其计数初始化为0(如果它不存在于map中)并且增加相同的

完成此步骤后,您将拥有一张地图

map = { 
  "tag1" : 2, //2 is the count value
  "tag3" : 3
}
  • 转换为数组标签

按出现次数的升序排序

var sortedArr = Object.keys( tagMap ).map( s => [ s , tagMap[s] ] ).sort( (a,b) => a[1] - b[1] );

<强> 解释

== 使用map

获取数组中Object.keys(map)的所有键

== 将所有密钥映射到另一个数组,以便每个项目都为[ tag, count ]

== 按计数值

对此数组进行排序

完成此步骤后,您将拥有一个已排序的数组,例如

sortedArr = [
  [ "tag3" , 3 ],
  [ "tag4" , 2 ],
  [ "tag2" , 2 ],
  [ "tag1" , 1 ],
]
  • 切片前三个值

var output = sortedArr.slice(-3);

<强>演示

&#13;
&#13;
var customers = [{
  "_id": "555e4125afb26872ac1cb814",
  "index": 0,
  "guid": "e7bd5b56-43d3-41cb-9742-aee4408a36c2",
  "isActive": false,
  "balance": "$3,868.37",
  "picture": "http://placehold.it/32x32",
  "age": 37,
  "eyeColor": "brown",
  "name": "Adele Mullen",
  "gender": "female",
  "company": "GAPTEC",
  "email": "adelemullen@gaptec.com",
  "phone": "+1 (860) 572-3603",
  "address": "775 Tapscott Street, Mammoth, South Dakota, 9956",
  "about": "Aliqua duis ex id excepteur duis aute non ipsum laborum. Duis exercitation aliquip sint irure consectetur ex enim veniam irure aliquip ipsum dolore cillum sunt. Ea dolor magna cupidatat sint laboris ipsum. Cillum quis nisi laboris officia consequat nulla dolor adipisicing eu. Quis ut nostrud non aliqua.\r\n",
  "registered": "2014-05-12T22:50:11 +05:00",
  "latitude": 30.620088,
  "longitude": -156.753814,
  "tags": ["cupidatat", "do", "irure", "proident", "sit", "nulla", "aute"],
  "friends": [{
    "id": 0,
    "name": "Justice Lara"
  }, {
    "id": 1,
    "name": "Duke Patrick"
  }, {
    "id": 2,
    "name": "Herring Hull"
  }, {
    "id": 3,
    "name": "Johnnie Berg"
  }],
  "greeting": "Hello, Adele Mullen! You have 8 unread messages.",
  "favoriteFruit": "banana"
}, {
  "_id": "555e4125030944f697e16ab7",
  "index": 1,
  "guid": "eb2bd6bb-d032-4ec1-9e45-8d34535f8cf4",
  "isActive": true,
  "balance": "$3,690.70",
  "picture": "http://placehold.it/32x32",
  "age": 26,
  "eyeColor": "green",
  "name": "Olga Newton",
  "gender": "female",
  "company": "INTERGEEK",
  "email": "olganewton@intergeek.com",
  "phone": "+1 (856) 522-3065",
  "address": "428 Division Avenue, Morriston, Illinois, 5540",
  "about": "Incididunt cupidatat incididunt aliquip ea voluptate nisi Lorem. Consectetur consectetur sunt laborum ad sit pariatur velit pariatur quis. Quis veniam ex eiusmod aute ex cupidatat id sunt. Eiusmod minim enim sit duis ipsum enim culpa id eu dolore consectetur. Laborum ex magna deserunt ullamco cillum nisi culpa dolore ullamco incididunt ut. Non incididunt culpa pariatur id deserunt deserunt amet excepteur consectetur nostrud. Elit sint sit reprehenderit minim ex id anim et nulla cupidatat ex.\r\n",
  "registered": "2014-11-24T23:10:56 +06:00",
  "latitude": -36.350505,
  "longitude": -173.287501,
  "tags": ["voluptate", "non", "amet", "do", "occaecat", "commodo", "in"],
  "friends": [{
    "id": 0,
    "name": "Cross Barnett"
  }, {
    "id": 1,
    "name": "Raquel Haney"
  }, {
    "id": 2,
    "name": "Cassandra Martin"
  }, {
    "id": 3,
    "name": "Shelly Walton"
  }],
  "greeting": "Hello, Olga Newton! You have 7 unread messages.",
  "favoriteFruit": "strawberry"
}, {
  "_id": "555e41251beb2fc79cbafff7",
  "index": 2,
  "guid": "3bfda455-d93f-4e70-9632-21504df89ede",
  "isActive": true,
  "balance": "$1,005.44",
  "picture": "http://placehold.it/32x32",
  "age": 35,
  "eyeColor": "blue",
  "name": "Shelly Walton",
  "gender": "female",
  "company": "TYPHONICA",
  "email": "shellywalton@typhonica.com",
  "phone": "+1 (806) 578-2712",
  "address": "934 Elm Avenue, Sidman, Utah, 1267",
  "about": "Irure labore ut officia veniam ad tempor labore. Eu ullamco elit magna veniam. Deserunt excepteur ullamco eiusmod nisi magna dolor sint minim occaecat. Consequat dolore consequat culpa excepteur non Lorem ut. Occaecat excepteur eiusmod dolor labore.\r\n",
  "registered": "2014-11-15T07:22:23 +06:00",
  "latitude": 70.637542,
  "longitude": 38.023956,
  "tags": ["laborum", "esse", "occaecat", "id", "ea", "non"],
  "friends": [{
    "id": 0,
    "name": "Cheryl Kent"
  }, {
    "id": 1,
    "name": "Greta Wells"
  }, {
    "id": 2,
    "name": "Gutierrez Waters"
  }, {
    "id": 3,
    "name": "Cooley Jimenez"
  }],
  "greeting": "Hello, Shelly Walton! You have 3 unread messages.",
  "favoriteFruit": "banana"
}, {
  "_id": "555e41253d951ad8d2d27b50",
  "index": 3,
  "guid": "ee28c73c-5692-4dba-96ba-3b695eb7122a",
  "isActive": true,
  "balance": "$2,491.36",
  "picture": "http://placehold.it/32x32",
  "age": 24,
  "eyeColor": "blue",
  "name": "Serena Odonnell",
  "gender": "female",
  "company": "ECOLIGHT",
  "email": "serenaodonnell@ecolight.com",
  "phone": "+1 (844) 559-3964",
  "address": "375 Beaver Street, Garfield, Maryland, 8966",
  "about": "Eu labore dolor ea reprehenderit duis laboris minim voluptate exercitation magna velit sunt. Proident adipisicing enim ut cupidatat. Irure ut tempor ea officia labore aliqua sint labore ipsum adipisicing magna aute. Deserunt voluptate aute minim ea nulla duis mollit anim.\r\n",
  "registered": "2014-12-03T08:18:32 +06:00",
  "latitude": 86.286967,
  "longitude": -98.561972,
  "tags": ["sint", "Lorem", "aliqua", "magna", "exercitation", "labore", "eu"],
  "friends": [{
    "id": 0,
    "name": "Deborah Carr"
  }, {
    "id": 1,
    "name": "Stein Simpson"
  }, {
    "id": 2,
    "name": "Stefanie Leblanc"
  }, {
    "id": 3,
    "name": "Tsing Tao"
  }],
  "greeting": "Hello, Serena Odonnell! You have 1 unread messages.",
  "favoriteFruit": "apple"
}, {
  "_id": "555e412508a72c3ba3cdf538",
  "index": 4,
  "guid": "a08d2523-bf5a-4c5e-8f53-dd8cbba5c505",
  "isActive": false,
  "balance": "$2,631.16",
  "picture": "http://placehold.it/32x32",
  "age": 25,
  "eyeColor": "brown",
  "name": "Morrison Strong",
  "gender": "male",
  "company": "COMTOURS",
  "email": "morrisonstrong@comtours.com",
  "phone": "+1 (855) 574-2926",
  "address": "555 Bowery Street, Foxworth, Virginia, 4758",
  "about": "Sunt proident exercitation anim eiusmod amet deserunt dolor sunt. Ipsum dolor anim do ut quis dolore nisi eiusmod. Laborum dolor consequat irure consectetur deserunt aliquip occaecat esse sunt pariatur consectetur. Elit sint consequat fugiat sint ad fugiat mollit. Nostrud do non veniam nisi veniam fugiat dolor anim adipisicing.\r\n",
  "registered": "2014-07-30T06:36:56 +05:00",
  "latitude": 75.061884,
  "longitude": 93.11415,
  "tags": ["fugiat", "magna", "ea", "sunt", "minim", "excepteur", "nisi"],
  "friends": [{
    "id": 0,
    "name": "Laurel Stanton"
  }, {
    "id": 1,
    "name": "Tricia Salinas"
  }, {
    "id": 2,
    "name": "Roxanne Day"
  }, {
    "id": 3,
    "name": "Cooley Jimenez"
  }],
  "greeting": "Hello, Morrison Strong! You have 7 unread messages.",
  "favoriteFruit": "apple"
}, {
  "_id": "555e4125970ae2387fab74ed",
  "index": 5,
  "guid": "990062ff-ab4f-4c3b-aad4-dbca366c22de",
  "isActive": true,
  "balance": "$1,527.76",
  "picture": "http://placehold.it/32x32",
  "age": 40,
  "eyeColor": "green",
  "name": "Buckner Kennedy",
  "gender": "male",
  "company": "SHEPARD",
  "email": "bucknerkennedy@shepard.com",
  "phone": "+1 (800) 524-3139",
  "address": "234 Kings Place, Darbydale, Wyoming, 8190",
  "about": "Cupidatat cupidatat commodo ut qui velit labore ea esse irure quis esse. Proident eu tempor amet proident amet consequat minim elit et tempor. Exercitation dolore aute nulla velit veniam qui eu. Tempor mollit elit magna cupidatat eu velit id consequat sint dolor qui. Nisi minim duis anim minim nulla in voluptate ea anim sit nostrud. Tempor commodo Lorem tempor aliqua est sint aliqua eu.\r\n",
  "registered": "2015-04-19T06:59:09 +05:00",
  "latitude": -89.386174,
  "longitude": 39.015288,
  "tags": ["sit", "sunt", "minim", "veniam", "cillum", "nisi", "enim"],
  "friends": [{
    "id": 0,
    "name": "Cooley Jimenez"
  }, {
    "id": 1,
    "name": "Mooney Hinton"
  }, {
    "id": 2,
    "name": "Stacy Ross"
  }, {
    "id": 3,
    "name": "Doyle Erickson"
  }],
  "greeting": "Hello, Buckner Kennedy! You have 8 unread messages.",
  "favoriteFruit": "banana"
}, {
  "_id": "555e4125ff554bdf2d6f080c",
  "index": 6,
  "guid": "2b5ad6ce-4a9b-4ec1-b869-cf0cac7c4d21",
  "isActive": false,
  "balance": "$1,453.63",
  "picture": "http://placehold.it/32x32",
  "age": 22,
  "eyeColor": "green",
  "name": "Doyle Erickson",
  "gender": "male",
  "company": "BLEENDOT",
  "email": "doyleerickson@bleendot.com",
  "phone": "+1 (976) 432-3644",
  "address": "182 Rockwell Place, Goldfield, Indiana, 8753",
  "about": "Veniam sunt amet amet dolor nostrud voluptate Lorem culpa est reprehenderit. Officia Lorem Lorem ut sit duis eu voluptate. Culpa aliqua sint in eiusmod. Duis incididunt sint velit ex ut excepteur. Deserunt nulla adipisicing minim minim cillum deserunt do tempor. Laboris nostrud cillum ea proident laboris do incididunt laborum. Eiusmod qui qui nulla velit do fugiat.\r\n",
  "registered": "2015-03-05T19:47:37 +06:00",
  "latitude": 72.253186,
  "longitude": -23.777045,
  "tags": ["dolore", "Lorem", "velit", "pariatur", "aliqua", "veniam"],
  "friends": [{
    "id": 0,
    "name": "Torres Nguyen"
  }, {
    "id": 1,
    "name": "Francine Melendez"
  }, {
    "id": 2,
    "name": "Johnnie Berg"
  }, {
    "id": 3,
    "name": "Olga Newton"
  }],
  "greeting": "Hello, Doyle Erickson! You have 10 unread messages.",
  "favoriteFruit": "banana"
}, {
  "_id": "123e4125ff554bdf2d6f080c",
  "index": 7,
  "guid": "5c5ad6ce-4a9b-4ec1-b869-cf0cac7c4d21",
  "isActive": true,
  "balance": "$1,253.63",
  "picture": "http://placehold.it/32x32",
  "age": 22,
  "eyeColor": "green",
  "name": "Doris Smith",
  "gender": "transgender",
  "company": "BLEENDOT",
  "email": "dorissmith@bleendot.com",
  "phone": "+1 (976) 432-3644",
  "address": "182 Rockwell Place, Goldfield, Indiana, 8753",
  "about": "Veniam sunt amet amet dolor nostrud voluptate Lorem culpa est reprehenderit. Officia Lorem Lorem ut sit duis eu voluptate. Culpa aliqua sint in eiusmod. Duis incididunt sint velit ex ut excepteur. Deserunt nulla adipisicing minim minim cillum deserunt do tempor. Laboris nostrud cillum ea proident laboris do incididunt laborum. Eiusmod qui qui nulla velit do fugiat.\r\n",
  "registered": "2015-03-05T19:47:37 +06:00",
  "latitude": 72.253186,
  "longitude": -23.777045,
  "tags": ["dolore", "Lorem", "velit", "pariatur", "aliqua", "veniam", "aute"],
  "friends": [{
    "id": 0,
    "name": "Buckner Kennedy"
  }, {
    "id": 1,
    "name": "Francine Melendez"
  }, {
    "id": 2,
    "name": "Johnnie Berg"
  }, {
    "id": 3,
    "name": "Olga Newton"
  }],
  "greeting": "Hello, Doris Smith! You have 10 unread messages.",
  "favoriteFruit": "banana"
}];



var topThreeTags = function(customers) {
  var output = [];
  var tagMap = {};
  customers.forEach(function(customer) {
    customer.tags.forEach(function(tag) {
      tagMap[tag] = (tagMap[tag] || 0) + 1;
    });
  });
  var sortedArr = Object.keys(tagMap).map(s => [s, tagMap[s]]).sort((a, b) => a[1] - b[1]);
  output = sortedArr.slice(-3);
  return output;
};

console.log(topThreeTags(customers));
&#13;
&#13;
&#13;

相关问题