You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Clojure中实现合并两个map向量的函数:同车型取最低价格

Solution for Merging Car Maps by Minimum Price

Alright, let's solve this problem where we need to merge two vectors of Clojure maps, keeping only the entry with the lowest :price for each :car value. Here's how to approach it step by step:

First, let's recap the requirements clearly:

  • We have two vectors of maps, each containing :id, :car, and :price keys
  • For entries with the same :car value, we keep the one with the smallest :price
  • All unique :car entries (no duplicates across inputs) should be retained as-is

Step-by-Step Approach

  1. Combine both input vectors: Merge all entries into a single sequence so we can process them uniformly.
  2. Group entries by :car: Cluster all maps that share the same car type together.
  3. Select the minimum price entry per group: For each car group, pick the map with the lowest :price value.
  4. Optional: Sort by :car: If you want the output ordered alphabetically by car type (matching your expected output), add a sort step.

Clojure Code Implementation

First, define your input vectors:

(def input1 [{:id 1 :car "A" :price 10} {:id 2 :car "B" :price 20} {:id 3 :car "C" :price 30}])
(def input2 [{:id 4 :car "A" :price 5} {:id 5 :car "B" :price 30} {:id 6 :car "D" :price 40}])

Then the merging function:

(defn merge-car-maps [first-maps second-maps]
  (->> (concat first-maps second-maps)
       (group-by :car)
       (map (fn [[_ car-group]]
              (apply min-key :price car-group)))
       (sort-by :car)))

Testing the Function

When you call the function with your inputs:

(merge-car-maps input1 input2)

You'll get exactly the expected output:

[{:id 4, :car "A", :price 5} {:id 2, :car "B", :price 20} {:id 3, :car "C", :price 30} {:id 6, :car "D", :price 40}]

How It Works

  • concat: Merges the two input vectors into one continuous sequence of maps.
  • group-by :car: Creates a map where each key is a car type (like "A"), and the value is a vector of all maps with that car type.
  • min-key :price: This function takes a key (:price) and a collection, returning the element with the smallest value for that key. Using apply here passes all elements of the car group to min-key.
  • sort-by :car: Sorts the final collection alphabetically by the :car key to match the order in your expected output. If you don't care about the order, you can omit this step.

内容的提问来源于stack exchange,提问作者Kami.Foo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:18:57