We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
js实现普通数组去重&json数组去重
The text was updated successfully, but these errors were encountered:
方法一 使用reduce及key的唯一性
/** * json数组去重 * @param {Array} jsonArray去重之前的数组 * @param {String} fieldName 需要去重的字段值 * @return {Array} 去重之后的数组 */ function uniqueJsonArrayByFieldName(jsonArray, fieldName) { let hash = {}; let uniqueArr = []; if(!(Object.prototype.toString.call(jsonArray).toLowerCase() == "[object array]")) return []; // 不是数组 uniqueArr = jsonArray.reduce((preVal, curVal) => { if(!(Object.prototype.toString.call(curVal).toLowerCase() == "[object object]")) return []; // 不是json对象 if(!curVal.hasOwnProperty(fieldName)) return []; // 没有fieldName属性 hash[curVal[fieldName]] ? '' : hash[curVal[fieldName]] = true && preVal.push(curVal); return preVal }, []); hash = null; return uniqueArr; }
方法二 循环
/** * json数组去重 * @param {Array} jsonArray去重之前的数组 * @param {String} fieldName 需要去重的字段值 * @return {Array} 去重之后的数组 */ function uniqueJsonArrayByFieldName(jsonArray, fieldName) { let dest = []; if(!(Object.prototype.toString.call(jsonArray).toLowerCase() == "[object array]")) return []; // 不是数组 for (let i = 0; i < jsonArray.length; i++) { let item = jsonArray[i]; if(!(Object.prototype.toString.call(item ).toLowerCase() == "[object object]")) return []; // 不是json对象 if(!item.hasOwnProperty(fieldName)) return []; // 没有fieldName属性 if (i == 0) { dest.push(item); } else { let filterData = dest.filter(function (f_item) { return f_item[fieldName] == item[fieldName]; }); if (filterData.length == 0) { dest.push(item); } } } return dest; }
Sorry, something went wrong.
No branches or pull requests
js实现普通数组去重&json数组去重
The text was updated successfully, but these errors were encountered: