如何删除数组中的重复属性值 - JavaScript?
javascriptweb developmentfront end technologyobject oriented programming
假设以下是我们的数组减法
var details = [ { studentName: "John", studentMarks: [78, 98] }, { studentName: "David", studentMarks: [87, 87] }, { studentName: "Bob", studentMarks: [48, 58] }, { studentName: "Sam", studentMarks: [98, 98] }, ]
我们需要删除重复的属性值,即 87 在上面重复出现。我们需要将其删除。
为此,使用 map() 的概念。
示例
以下是代码 −
var details = [ { studentName: "John", studentMarks: [78, 98] }, { studentName: "David", studentMarks: [87, 87] }, { studentName: "Bob", studentMarks: [48, 58] }, { studentName: "Sam", studentMarks: [98, 98] }, ] details.map(tempObj => { if (typeof (tempObj.studentMarks) == 'object') { tempObj.studentMarks = [... new Set(tempObj.studentMarks)] if (tempObj.studentMarks.length == 1) { tempObj.studentMarks = tempObj.studentMarks[0] } } }); console.log(details);
要运行上述程序,您需要使用以下命令 −
node fileName.js.
这里,文件名是 demo292.js。
输出
这将在控制台上产生以下输出 −
PS C:\Users\Amit\javascript-code> node demo292.js [ { studentName: 'John', studentMarks: [ 78, 98 ] }, { studentName: 'David', studentMarks: 87 }, { studentName: 'Bob', studentMarks: [ 48, 58 ] }, { studentName: 'Sam', studentMarks: 98 } ]