如何根据值的权重找到最相似的数组?

我有一个具有给定用户的对象。

const user = [{ id: '1',city: 'Paris',cuisine: 'italian',allergic: 'no',budget: '50',hasChildren: 'yes' }]

还有带有餐厅的一系列对象。我想找到这个用户最符合他要求的餐厅。

const restaurants: [
 {
  cuisine: 'mexican',averageCost: '30',children: 'no'
 },{
  cuisine: 'italian',children: 'yes'
 }
]

因此,第二家餐厅更适合用户,因此它应该显示为第一家。每个按键都应具有一定的重量,因为美食比价格更重要,因此应该获得更高的分数。我该如何实现?是否有任何算法可以在JavaScript中做到这一点?

dyc765 回答:如何根据值的权重找到最相似的数组?

我在下面给出了一个简单的实现。这个想法是根据scoring functionuser data为您的餐厅创建一个restaurant data.,然后使用该功能为餐厅评分对餐厅进行排序。对后代进行评分,以在顶部获得最“最近”的餐厅。

您可以根据需要为分数分配权重。

// Given
const restaurants = [
 {
  cuisine: 'mexican',averageCost: '30',children: 'no'
 },{
  cuisine: 'italian',children: 'yes'
 }
];

const user = [{ id: '1',city: 'Paris',cuisine: 'italian',allergic: 'no',budget: '50',hasChildren: 'yes' }];


const calculateScore = (user,restaurant) => {
    // you can fine tune the values for the weights yourself

    // asume that children score gives 1
    const childrenScore = (user.hasChildren === restaurant.children) ? 1 : 0;

    // asume that cuisine score gives 1
    const cuisineScore = (user.cuisine === restaurant.cuisine) ? 1 : 0;

    // asume that cost score gives the absolute difference
    const costScore = Math.abs(parseInt(restaurant.averageCost) - parseInt(user.budget));

    return childrenScore + cuisineScore + costScore;
}

const sortedRestaurants = restaurants.sort((rA,rB) => {
    const rAScore = calculateScore(user[0],rA);
    const rBScore = calculateScore(user[0],rB);
    return rBScore - rAScore; // sort DESC by score
});

console.log(sortedRestaurants)
,

以下是您可以执行的操作的简短摘要。

const user = [{ id: '1',hasChildren: 'yes' }];
const restaurants = [
    {
     cuisine: 'mexican',children: 'no'
    },{
     cuisine: 'italian',children: 'yes'
    }
]

const orderedRestaurants = restaurants.map(r => {
    return {
        ...r,score: 0 +
        (r.cuisine === user[0].cuisine ? 4 : 0) +
        (r.averageCost <= user[0].budget ? 8 : 0) +
        (r.children === 'no' && user[0].hasChildren === 'yes' ? 0 : 3)
    }
}).sort((a,b) => b.score - a.score);

console.log(orderedRestaurants);

因此,我们需要根据特定条件为每家餐厅分配分数。我已经在函数中分配了权重,您可以将其移到对象之外以进行动态评分。

在此示例中,如果菜色符合用户的兴趣,我们将给他们4分;如果平均费用低于或等于预算,则给他们8分;如果用户有孩子和餐厅,则给他们3分允许孩子。随时根据需要编辑评分系统,但希望这可以帮助您入门。

本文链接:https://www.f2er.com/3163941.html

大家都在问