Skip to content
New issue

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数组去重 #65

Open
artdong opened this issue Aug 5, 2020 · 1 comment
Open

js实现普通数组去重&json数组去重 #65

artdong opened this issue Aug 5, 2020 · 1 comment
Labels
js javascript

Comments

@artdong
Copy link
Collaborator

artdong commented Aug 5, 2020

js实现普通数组去重&json数组去重

@artdong artdong added the js javascript label Aug 5, 2020
@artdong
Copy link
Collaborator Author

artdong commented Aug 5, 2020

普通数组去重(#24)

json数组去重

方法一 使用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;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
js javascript
Projects
None yet
Development

No branches or pull requests

1 participant