最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - After using .filter() on a array of objects, I wants to create a third array that shows what data was matching - St

programmeradmin4浏览0评论

I have an array of objects that have alot of values pulled from an excel sheet and I am using .filter() to compare certain keys from main object to return a new array.

  • if this returned array is 0 I dont combine the excess data into the original object.
  • if this returned array is 1 I spread the keys into the current object and replace what I need to later.

But if this array is more than 1 I want to show the user that these values were found as duplicates and tell them what was the duplicate I found. So they can fix the sheets and retry the code

/* Current user I am getting from for looping the firstSheet */
let currentUser = {'First Name': 'Billy', 'Last Name': 'Bob', 'Member Number': 3333,'Home Phone': 9764582917, 'Cell Phone': 2345677123, 'Day Phone': 9928844574, 'Email': '[email protected]', 'plan price': '10.10' }

/* this is found from checking further in the first sheet by a small for loop that runs as it finds duplicates, ussaly there is only 1 object in this. There is a line per plan*/
let dupeArray = [{'First Name': 'Billy', 'Last Name': 'Bob', 'Member Number': 1111,'Home Phone': 9764582917, 'Cell Phone': 2345677123, 'Day Phone': 9928844574, 'Email': '[email protected]', 'plan Price': '10.10'  }]

let secondSheet = [
    {'First Name': 'Billy', 'Last Name': 'Bob', 'plan1': 1111, 'plan2': 2222, 'plan3': 3333, 'Home Phone': 9764582917, 'Cell Phone': 2345677123, 'Day Phone': 9928844574, 'Email': '[email protected]', 'plan1 Price': '10.10', 'plan2 Price': '10.10', 'plan3 Price': '10.10'  },
    {'First Name': 'Benny', 'Last Name': 'Socks', 'plan1': 5315, 'plan2': 5562, 'plan3': 3333, 'Home Phone': 1122331467, 'Cell Phone': 9867485926, 'Day Phone': 1759603752, 'Email': '[email protected]', 'plan1 Price': '10.10', 'plan2 Price': '10.10', 'plan3 Price': '10.10'  },
    {'First Name': 'Sara', 'Last Name': 'Jones', 'plan1': 5645, 'plan2': 5522, 'plan3': 6678, 'Home Phone': 6672854673, 'Cell Phone': 7766552897, 'Day Phone': 9856301788, 'Email': '[email protected]', 'plan1 Price': '10.10', 'plan2 Price': '10.10', 'plan3 Price': '10.10'  },
    {'First Name': 'Jones', 'Last Name': 'Smith', 'plan1': 2344, 'plan2': 7766, 'plan3': 8763, 'Home Phone': 2221113323, 'Cell Phone': 7766552897, 'Day Phone': 1115566779, 'Email': '[email protected]', 'plan1 Price': '10.10', 'plan2 Price': '10.10', 'plan3 Price': '10.10'  },
]

let existingContacts;
function handleUpdate(){
    existingContacts = secondSheet.filter((currContact) => {
        if( [currContact['plan1'], currContact['plan2'], currContact['plan3']].indexOf(currentUser['memberNumber']) > -1 || currContact['Email'] === currentUser['Email'] || currContact['Cell Phone'] === currentUser['Cell Phone'] ) {
            return true;
        } else {
            for (let a = 0; a < dupeArray.length; a++) {
                if([currContact['plan1'], currContact['plan2'], currContact['plan3'],].indexOf(dupeArray[a]['Member Number']) > -1) {
                    return true
                }
            }
            return false;
        }
    })
    if (existingContacts.length === 1) {return true;}
    else if (existingContacts.length > 1) { /* Wanna push was found in the .filter() here */ return false; }
    else { return false; }
}

console.log(handleUpdate())
/* This is just to explain why the function itself returns a boolean */
// filteredSheet.push({
//     ...(handleUpdate() && existingContacts[0]),
//     /* then I replace what i need to from currentUser here */
// })

That is most of the function. I have some minor things converting the values so they dont error like emails being blank and stuff

I just want to be able to display to the user what was found and show them what was the duplicate in a seperate modal I got set up already

so example would be Error Log:

Billy Bob: duplicate with Benny Socks at Member Number
...etc

Sorry for it being long.

Current idea I can only think of (will need to declare modalArray at the top of function tho)

    else if (existingContacts.length > 1) { 
        for(let b=0; b < existingContacts.length; b++) {
            if([existingContacts[b]['plan1'], existingContacts[b]['plan2'], existingContacts[b]['plan3']].indexOf(currentUser['memberNumber']) > -1) {
                modalArray.push({ currentUserFirstName: currentUser['First Name'], currentUserlastName: currentUser['Last Name'],  issueFound: 'Member Number', currContactFirstName: existingContacts[b]['First Name'], currContactLastName: existingContacts[b]['Last Name']})
            
            } else if (existingContacts[b]['Email'] === currentUser['Email']) { 
                modalArray.push({ currentUserFirstName: currentUser['First Name'], currentUserlastName: currentUser['Last Name'],  issueFound: 'Email', currContactFirstName: existingContacts[b]['First Name'], currContactLastName: existingContacts[b]['Last Name']}) 
            
            } else if (existingContacts[b]['Cell Phone'] === currentUser['Cell Phone']) {
                modalArray.push({ currentUserFirstName: currentUser['First Name'], currentUserlastName: currentUser['Last Name'],  issueFound: 'Cell Phone', currContactFirstName: existingContacts[b]['First Name'], currContactLastName: existingContacts[b]['Last Name']}) 
            
            } else {
                for (let c = 0; c < dupeArray.length; c++) { // lol
                    if([existingContacts[b]['plan1'], existingContacts[b]['plan2'], existingContacts[b]['plan3'],].indexOf(dupeArray[c]['Member Number']) > -1) {
                        modalArray.push({ currentUserFirstName: currentUser['First Name'], currentUserlastName: currentUser['Last Name'],  issueFound: 'Member Number', currContactFirstName: existingContacts[b]['First Name'], currContactLastName: existingContacts[b]['Last Name']}) 
                    }
                }
            }
        }
        return false;
    }

but I feel that there is a better way to do this. as this just seems like brute force

I just want to have the array I can send to my Modal Component and map it there

I have an array of objects that have alot of values pulled from an excel sheet and I am using .filter() to compare certain keys from main object to return a new array.

  • if this returned array is 0 I dont combine the excess data into the original object.
  • if this returned array is 1 I spread the keys into the current object and replace what I need to later.

But if this array is more than 1 I want to show the user that these values were found as duplicates and tell them what was the duplicate I found. So they can fix the sheets and retry the code

/* Current user I am getting from for looping the firstSheet */
let currentUser = {'First Name': 'Billy', 'Last Name': 'Bob', 'Member Number': 3333,'Home Phone': 9764582917, 'Cell Phone': 2345677123, 'Day Phone': 9928844574, 'Email': '[email protected]', 'plan price': '10.10' }

/* this is found from checking further in the first sheet by a small for loop that runs as it finds duplicates, ussaly there is only 1 object in this. There is a line per plan*/
let dupeArray = [{'First Name': 'Billy', 'Last Name': 'Bob', 'Member Number': 1111,'Home Phone': 9764582917, 'Cell Phone': 2345677123, 'Day Phone': 9928844574, 'Email': '[email protected]', 'plan Price': '10.10'  }]

let secondSheet = [
    {'First Name': 'Billy', 'Last Name': 'Bob', 'plan1': 1111, 'plan2': 2222, 'plan3': 3333, 'Home Phone': 9764582917, 'Cell Phone': 2345677123, 'Day Phone': 9928844574, 'Email': '[email protected]', 'plan1 Price': '10.10', 'plan2 Price': '10.10', 'plan3 Price': '10.10'  },
    {'First Name': 'Benny', 'Last Name': 'Socks', 'plan1': 5315, 'plan2': 5562, 'plan3': 3333, 'Home Phone': 1122331467, 'Cell Phone': 9867485926, 'Day Phone': 1759603752, 'Email': '[email protected]', 'plan1 Price': '10.10', 'plan2 Price': '10.10', 'plan3 Price': '10.10'  },
    {'First Name': 'Sara', 'Last Name': 'Jones', 'plan1': 5645, 'plan2': 5522, 'plan3': 6678, 'Home Phone': 6672854673, 'Cell Phone': 7766552897, 'Day Phone': 9856301788, 'Email': '[email protected]', 'plan1 Price': '10.10', 'plan2 Price': '10.10', 'plan3 Price': '10.10'  },
    {'First Name': 'Jones', 'Last Name': 'Smith', 'plan1': 2344, 'plan2': 7766, 'plan3': 8763, 'Home Phone': 2221113323, 'Cell Phone': 7766552897, 'Day Phone': 1115566779, 'Email': '[email protected]', 'plan1 Price': '10.10', 'plan2 Price': '10.10', 'plan3 Price': '10.10'  },
]

let existingContacts;
function handleUpdate(){
    existingContacts = secondSheet.filter((currContact) => {
        if( [currContact['plan1'], currContact['plan2'], currContact['plan3']].indexOf(currentUser['memberNumber']) > -1 || currContact['Email'] === currentUser['Email'] || currContact['Cell Phone'] === currentUser['Cell Phone'] ) {
            return true;
        } else {
            for (let a = 0; a < dupeArray.length; a++) {
                if([currContact['plan1'], currContact['plan2'], currContact['plan3'],].indexOf(dupeArray[a]['Member Number']) > -1) {
                    return true
                }
            }
            return false;
        }
    })
    if (existingContacts.length === 1) {return true;}
    else if (existingContacts.length > 1) { /* Wanna push was found in the .filter() here */ return false; }
    else { return false; }
}

console.log(handleUpdate())
/* This is just to explain why the function itself returns a boolean */
// filteredSheet.push({
//     ...(handleUpdate() && existingContacts[0]),
//     /* then I replace what i need to from currentUser here */
// })

That is most of the function. I have some minor things converting the values so they dont error like emails being blank and stuff

I just want to be able to display to the user what was found and show them what was the duplicate in a seperate modal I got set up already

so example would be Error Log:

Billy Bob: duplicate with Benny Socks at Member Number
...etc

Sorry for it being long.

Current idea I can only think of (will need to declare modalArray at the top of function tho)

    else if (existingContacts.length > 1) { 
        for(let b=0; b < existingContacts.length; b++) {
            if([existingContacts[b]['plan1'], existingContacts[b]['plan2'], existingContacts[b]['plan3']].indexOf(currentUser['memberNumber']) > -1) {
                modalArray.push({ currentUserFirstName: currentUser['First Name'], currentUserlastName: currentUser['Last Name'],  issueFound: 'Member Number', currContactFirstName: existingContacts[b]['First Name'], currContactLastName: existingContacts[b]['Last Name']})
            
            } else if (existingContacts[b]['Email'] === currentUser['Email']) { 
                modalArray.push({ currentUserFirstName: currentUser['First Name'], currentUserlastName: currentUser['Last Name'],  issueFound: 'Email', currContactFirstName: existingContacts[b]['First Name'], currContactLastName: existingContacts[b]['Last Name']}) 
            
            } else if (existingContacts[b]['Cell Phone'] === currentUser['Cell Phone']) {
                modalArray.push({ currentUserFirstName: currentUser['First Name'], currentUserlastName: currentUser['Last Name'],  issueFound: 'Cell Phone', currContactFirstName: existingContacts[b]['First Name'], currContactLastName: existingContacts[b]['Last Name']}) 
            
            } else {
                for (let c = 0; c < dupeArray.length; c++) { // lol
                    if([existingContacts[b]['plan1'], existingContacts[b]['plan2'], existingContacts[b]['plan3'],].indexOf(dupeArray[c]['Member Number']) > -1) {
                        modalArray.push({ currentUserFirstName: currentUser['First Name'], currentUserlastName: currentUser['Last Name'],  issueFound: 'Member Number', currContactFirstName: existingContacts[b]['First Name'], currContactLastName: existingContacts[b]['Last Name']}) 
                    }
                }
            }
        }
        return false;
    }

but I feel that there is a better way to do this. as this just seems like brute force

I just want to have the array I can send to my Modal Component and map it there

Share Improve this question edited Feb 17 at 5:02 Zu0s asked Feb 17 at 3:58 Zu0sZu0s 212 bronze badges 9
  • 3 You should post an example of a typical array of objects (eg secondSheet) and your function in a minimal reproducible example. – zer00ne Commented Feb 17 at 4:08
  • 1 @zer00ne Sorry. Just added some more detail in the code and more explanation for my thinking of how to do this. Hopefully this can help – Zu0s Commented Feb 17 at 5:03
  • Shouldn't the users from the secondSheet have member_numbers as well? Every person in your er...db? should have a unique member_number. Trying to differentiate people by their last and first names could be problematic. – zer00ne Commented Feb 17 at 9:09
  • Anyways your biggest problem is that filter() doesn't return a boolean, it returns the actual user if a condition is true. I think it would be better if you actually have an object that tracks all users and their duped property/values and assign a unique number to all members involved. That way you can quickly find all of them. If you just have true and false then you'd have to go back for the actual details with another function. – zer00ne Commented Feb 17 at 9:17
  • Aside: Instead of testing array.indexOf(val) > -1 use array.includes(val) – Barmar Commented Feb 17 at 16:28
 |  Show 4 more comments

1 Answer 1

Reset to default 0

If I reduce your problem, what you are asking is how to compare 2 objects (perhaps n times) and find what makes them match.

Let's write something.

function compareObjectsByKeys(obj1, obj2, keys) {
  var arr_matches = [];
  for (const key of keys) {
    if (obj1[key] == obj2[key]) {
      arr_matches.push(key)
    }
  }
  return arr_matches;
}

const obj1 = {
  name: 'John',
  age: 30,
  city: 'New York',
  country: "us"
};
const obj2 = {
  name: 'John',
  age: 30,
  city: 'Los Angeles',
  country: "us"
};

const obj3 = {
  name: 'Willcox',
  age: 24,
  city: 'Los Angeles',
  country: "us"
};

const keysToCompare = ['name', 'age', 'city'];

console.log("obj1 and obj2 match by: " + compareObjectsByKeys(obj1, obj2, keysToCompare))
console.log("obj1 and obj3 match by: " + compareObjectsByKeys(obj1, obj3, keysToCompare))
console.log("obj2 and obj3 match by: " + compareObjectsByKeys(obj2, obj3, keysToCompare))

And of course you can run on array and run this comparison. Let me know if you need help with that as well.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论