[英]Remove duplicates in the array using an object method
I'm curious how you'd be able to do this by utilizing an object method.我很好奇您如何通过使用 object 方法来做到这一点。 Is it possible?
可能吗?
function removeDuplicates(arr) { var result = []; for (var i = 0; i < arr.length; i++) { if (result.indexOf(arr[i]) === -1) { result.push(arr[i]); } } return result; } console.log(removeDuplicates(['Mike', 'Mike', 'Paul'])); // returns ["Mike", "Paul"]
You could take an object and return only the keys.您可以使用 object 并仅返回密钥。
function removeDuplicates(arr) { const seen = {}; for (let i = 0; i < arr.length; i++) seen[arr[i]] = true; return Object.keys(seen); } console.log(removeDuplicates(["Mike", "Mike", "Paul"])); // ["Mike", "Paul"]
Yes, you could use built-in Set()
是的,您可以使用内置的
Set()
const data = ["Mike", "Mike", "Paul"] const res = Array.from(new Set(data)) console.log(res)
You could utilize by making it a method of the array您可以通过使其成为数组的方法来利用
Array.prototype.removeDuplicates = function() { return Array.from(new Set(this)) } const data = ["Mike", "Mike", "Paul"] console.log(data.removeDuplicates())
If i understood correctly, you could extend the Array
object with a removeDuplicates()
method, just like this:如果我理解正确,您可以使用
removeDuplicates()
方法扩展Array
object,就像这样:
if (!Array.prototype.removeDuplicates) { // Check if the Array object already has a removeDuplicates() method
Array.prototype.removeDuplicates = function() {
let result = [];
for(var i = 0; i < this.length; i++){
if(result.indexOf(this[i]) === -1) {
result.push(this[i]);
}
}
return result;
}
}
const arr = ["Mike", "Mike", "Paul"];
console.log(arr.removeDuplicates()); // Call the new added method
function removeDuplicates(arr) { return Object.keys( arr.reduce( (val, cur) => ({...val, [cur]: true }), {} ) ); } console.log(removeDuplicates(['Mike', 'Mike', 'Paul']));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.