【问题标题】:Matching values in javascript arraysjavascript数组中的匹配值
【发布时间】:2017-01-10 15:00:47
【问题描述】:

在我检查这篇文章之前:How can I find matching values in two arrays? 但这对我没有帮助。我真的不明白。所以也许如果我在这里解释我的问题,有人可以帮助我解决它。

我有一个学校项目(我应该根据用户的位置、标签、人气分数等来匹配用户。 在对这两个位置使用算法之前,我想要第一个非精确排序。所以基本上我想比较'Paris'和'Paris'这样的两个值)

我的搜索函数返回一个 [],里面有两个 {},所以有两个人与我的第一个搜索值(性别)匹配

我正在使用 Node.js,我的数据库是 MySQL,到目前为止,我的函数正在使用回调和 Promise。

所以这是我的第一个对象(它包含我的搜索者的信息)

[ RowDataPacket {
id: 34,
username: 'natedogg',
latitude: 48.8835,
longitude: 2.3219,
country: 'France',
city: 'Paris',
zipcode: 75017 } ]

这是第二个(它包含 2 个用户)

[ RowDataPacket {
id: 33,
username: 'pablito',
latitude: 48.8921,
longitude: 2.31922,
country: 'France',
city: 'Paris',
zipcode: 75017 },
RowDataPacket {
id: 35,
username: 'tupac',
latitude: 48.8534,
longitude: 2.3488,
country: 'France',
city: 'levallois',
zipcode: 92300 } ]

我没有这些数据,我如何检查我的搜索者的位置是否 == 我的 otherUsersLocation(即使它们超过 1 个位置) 感谢您的帮助!

【问题讨论】:

  • 我试过 firstArray[0].city == secondArray[0].city. 但这里我在第二个数组中有两个 .city 所以它会匹配第一个而不是第二个。
  • @Cruiser 我也尝试过进一步的解决方案,但它不起作用。我做了for (city in potentialsLocation) { for (city in searcherLoc) { if (city === searcherLoc[0].[city]) { console.log("working ?"); } } } 我已经修改了我的数据库中的值,所以它应该可以工作,但是我不能记录任何东西

标签: javascript mysql node.js


【解决方案1】:

我为您编写了一些代码,该代码有效,您应该能够将其应用于您的情况。基本上,我们只是遍历我们想要搜索的对象并查看“城市”属性。我重命名了一些变量以使发生的事情更清楚。

var data = {
    id: 34,
    username: 'natedogg',
    latitude: 48.8835,
    longitude: 2.3219,
    country: 'France',
    city: 'Paris',
    zipcode: 75017 
};

var searchable = [{
    id: 33,
    username: 'pablito',
    latitude: 48.8921,
    longitude: 2.31922,
    country: 'France',
    city: 'Paris',
    zipcode: 75017 },
    {
    id: 35,
    username: 'tupac',
    latitude: 48.8534,
    longitude: 2.3488,
    country: 'France',
    city: 'levallois',
    zipcode: 92300 
}];

// this array is just to save obj when we have a match
var found =[];
// loop through each element in our searchable array
for(var i=0;i<searchable.length;++i){
    if(data["city"] == searchable[i]["city"]){
       // did we find it? push it onto the found array
       console.log("found: " + searchable[i]["city"]);
       found.push(searchable[i]["username"]);}
}
// look to see if we got what we wanted
console.log(found);

您可以按照相同的过程来匹配数据中的任何内容。

【讨论】:

  • 谢谢!这正是我想要的!今天下午,我设法用几分钟前刚刚发布的解决方案解决了我的问题。但我会记住你的,因为我会再次使用这个想法
  • 嘿!我只是想告诉你,你的想法运作良好。感谢您的帮助。我今天做了类似的事情,但它不起作用,基本上这是相同的想法,我想在两个数组之间找到一些匹配的值,但我无法在我的数组值上正确循环。如果你也能帮助我解决这个问题,那就太好了!
【解决方案2】:

这就是我设法在我的数组中找到匹配值的方法 if (SecondArray){ // console.log(SecondArray.length); SecondArray.forEach(function(element) { if (firstArray[0].city === element.city) { console.log("element); } }) }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-23
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    • 2020-07-01
    相关资源
    最近更新 更多