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

如何排序多维数组,使name为'keyboard'的子数组居首?

How to Move the 'keyboard' Subarray to the Front of a Multidimensional Array

Absolutely! There are a bunch of straightforward ways to pull this off, depending on which programming language you're working with. Let's break down the most common approaches for the two most popular languages:

JavaScript Solutions

1. Filter + Concatenation (Best for Performance)

This method splits your array into two groups—your target 'keyboard' item(s) and everything else—then glues them back together with the target group first. It’s efficient (O(n) time complexity) and easy to read.

const arr = [
  { name: 'mouse', price: 20 },
  { name: 'keyboard', price: 50 },
  { name: 'monitor', price: 200 }
];

// Option 1: Move ONLY the FIRST 'keyboard' item to the front
const keyboardItem = arr.find(item => item.name === 'keyboard');
const restItems = arr.filter(item => item.name !== 'keyboard');
const sortedArr = keyboardItem ? [keyboardItem, ...restItems] : arr;

// Option 2: Move ALL 'keyboard' items to the front
const keyboardItems = arr.filter(item => item.name === 'keyboard');
const otherItems = arr.filter(item => item.name !== 'keyboard');
const sortedArrAll = [...keyboardItems, ...otherItems];
  • Pro tip: Always check if keyboardItem exists before concatenating—this avoids errors if there’s no 'keyboard' entry in your array.

2. Using sort() (Concise, Less Efficient for Large Arrays)

If you prefer a one-liner, the sort() method works too. Just assign a priority value to the 'keyboard' item so it gets sorted to the top.

// Create a copy of the array first to avoid modifying the original
const sortedArr = [...arr].sort((a, b) => {
  if (a.name === 'keyboard') return -1; // Push a to front
  if (b.name === 'keyboard') return 1; // Push b to front relative to a
  return 0; // Keep other items in their original order
});
  • Note: sort() is an in-place method, so spreading the array ([...arr]) ensures your original data stays intact. This is O(n log n) time, which is fine for small arrays but less ideal for large datasets.

3. Modify the Original Array In-Place

If you need to tweak the original array instead of creating a new one, use findIndex() + splice() + unshift():

const index = arr.findIndex(item => item.name === 'keyboard');
if (index !== -1) {
  const [keyboardItem] = arr.splice(index, 1); // Remove the item from its current position
  arr.unshift(keyboardItem); // Add it to the front
}

Python Solutions

1. List Comprehension + Concatenation

Just like in JavaScript, splitting and concatenating is a solid approach here.

arr = [
    {'name': 'mouse', 'price': 20},
    {'name': 'keyboard', 'price': 50},
    {'name': 'monitor', 'price': 200}
]

# Option 1: Move ONLY the FIRST 'keyboard' item to the front
keyboard_item = next((item for item in arr if item['name'] == 'keyboard'), None)
rest_items = [item for item in arr if item['name'] != 'keyboard']
sorted_arr = [keyboard_item] + rest_items if keyboard_item else arr

# Option 2: Move ALL 'keyboard' items to the front
keyboard_items = [item for item in arr if item['name'] == 'keyboard']
other_items = [item for item in arr if item['name'] != 'keyboard']
sorted_arr_all = keyboard_items + other_items
  • next() grabs the first matching item, and the None fallback prevents errors if no 'keyboard' exists.

2. Using sorted() with a Custom Key

Python’s sorted() function accepts a custom key to define sorting order—super concise for this use case:

sorted_arr = sorted(arr, key=lambda x: 0 if x['name'] == 'keyboard' else 1)
  • This works because items with a key of 0 are sorted before those with 1. Python’s sorted() is stable, so other items will keep their original relative order.

3. Modify the Original Array In-Place

To adjust the original list directly, use enumerate() to find the index, then pop() and insert():

for i, item in enumerate(arr):
    if item['name'] == 'keyboard':
        arr.insert(0, arr.pop(i))
        break  # Remove this line if you want to move ALL 'keyboard' items to the front

Quick Notes

  • Always handle cases where there’s no 'keyboard' entry—this prevents unexpected None values or empty arrays.
  • Choose the method based on your needs: prioritize performance with filter/concatenation for large arrays, or go for conciseness with sort()/sorted() for small datasets.

内容的提问来源于stack exchange,提问作者Dylan van der Graaf

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:54:49