映射并返回_.uniq值而无需重复

时间:2018-08-14 14:17:57

标签: javascript arrays reactjs ecmascript-6 lodash

我正在进行一些映射...在我的示例中,我尝试通过添加<h3 key={i}>{_.uniq(person.name)}</h3> lodash的快捷方式仅返回重复值一次。从输出中可以看到,它从其对象数组返回重复的值。

{Object.keys(result).map((item, index) =>
    <div key={index} className="report">
        <div className="contact-item">
            {result[item].map((person, i) =>
                <h3 key={i}>{_.uniq(person.name)}</h3> 
               //OUTPUT "tom"
               //OUTPUT "GregGreg"
               //OUTPUT "Phil"
               //OUTPUT "timtim"
            )}
        </div>
    </div>
)}

result = 
0: {Number: 1, newNumber:"1", name: "tom" }
1: [{Number: 2, newNumber: "2", name: "Greg" }, {Number: 2, newNumber: "4", name: "Greg" }]
2: {Number: 3, newNumber: "3", name: "Phil" }
3: [{Number: 4, newNumber: "4", name: "tim" }, {Number: 2, newNumber: "3", name: "tim" }]

我只想返回“ tim”和“ Greg”一次作为重复项,因此不是唯一的。 _.uniq声明不执行任何操作。我尝试了其他lodash声明,例如union等...和uniqBy。任何帮助,将不胜感激。谢谢

3 个答案:

答案 0 :(得分:0)

假设您的源数据与结果数据相同,则可以执行以下操作:

_.chain(people).flatten().uniqBy('name').value()

此lodash语句将使数组变平,然后基于名称字段返回不同的值。我使用了lodash的链函数来使代码更简洁。

在此示例中可以看到此工作的示例:

https://repl.it/@8enSmith/ExemplarySereneToolbox

答案 1 :(得分:0)

使用lodash可以得到想要的东西。以下是一些示例:

var people = [
[{Number: 1, newNumber:"1", name: "tom" }],
[{Number: 2, newNumber: "2", name: "Greg" }, {Number: 2, newNumber: "4", name: "Greg" }],
[{Number: 3, newNumber: "3", name: "Phil" }],
[{Number: 4, newNumber: "4", name: "tim" }, {Number: 2, newNumber: "3", name: "tim" }]
]

console.log(_.chain(people).flatten().uniqBy('name').value())
console.log(_.chain(people).flatten().sortedUniqBy('name').value())

// this would pivot and keep the arrays as children
console.log(_.chain(people).flatten().groupBy('name').value()) 

// With loadsh/fp you could flow it
// console.log(_.flow(_.flatten, _.uniqBy('name'))(people))
// console.log(_.flow(_.flatten, _.sortedUniqBy('name'))(people))
// console.log(_.flow(_.flatten, _.groupBy('name'))(people))
  
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

答案 2 :(得分:0)

为了获得理想的结果,我要做的就是.slice(0, 1)带回一件物品。

{Object.keys(result).map((item, index) =>
    <div key={index} className="report">
        <div className="contact-item">
            {result[item].map((person, i) =>
                <h3 key={i}>{_.uniq(person.name)}</h3> 
               //OUTPUT "tom"
               //OUTPUT "GregGreg"
               //OUTPUT "Phil"
               //OUTPUT "timtim"
            ).slice(0, 1)}
        </div>
    </div>
)}