求基于JavaScript/Lodash的数组比较、索引定位及JSON排序方案
Hey there! Let's break down each of your array-related tasks with both vanilla JavaScript and Lodash solutions—since sometimes Lodash cuts down on boilerplate, but it's always good to know the native approach too.
1. 数组的比较与排序基础
First, let's cover the fundamentals of array comparison and sorting in JS:
数组比较
For simple value-based equality (checking if two arrays have identical values in the same order), use this native function:
function arraysAreEqual(arr1, arr2) { if (arr1.length !== arr2.length) return false; return arr1.every((val, index) => val === arr2[index]); } // Example usage arraysAreEqual([1,2,3], [1,2,3]); // true arraysAreEqual([1,2], [1,2,3]); // false
For arrays of objects (like your later tasks), you'll need to check specific properties—we'll dive into that next.
数组排序
Native JS has the sort() method, but remember to pass a comparator function for numeric/object sorting (otherwise it sorts lexicographically):
// Sort numbers ascending const numbers = [3,1,4,1,5]; numbers.sort((a,b) => a - b); // [1,1,3,4,5] // Sort objects by a property const items = [{name: "Banana", price: 2}, {name: "Apple", price: 1}]; items.sort((a,b) => a.price - b.price); // Sorts by price ascending
With Lodash, you get built-in deep comparison and cleaner object sorting:
// Deep equality check for objects/arrays of objects _.isEqual([{x:1,y:2}, {x:3,y:4}], [{x:1,y:2}, {x:3,y:4}]); // true // Sort objects by property with less code _.sortBy(items, 'price'); // Same result as the native object sort example
2. 匹配两个数组中x/y相等元素的索引
Assuming array1 and array2 are arrays of objects with x and y properties (e.g., array1 = [{x: 5, y: 10}, ...]), here's how to collect indices where both properties match at the same position:
Vanilla JavaScript Solution
function getMatchingIndices(array1, array2) { const matchingIndices = []; if (array1.length !== array2.length) return matchingIndices; for (let i = 0; i < array1.length; i++) { const item1 = array1[i]; const item2 = array2[i]; if (item1.x === item2.x && item1.y === item2.y) { matchingIndices.push(i); } } return matchingIndices; } // Example usage const array1 = [{x:1,y:2}, {x:3,y:4}, {x:5,y:6}]; const array2 = [{x:1,y:2}, {x:3,y:5}, {x:5,y:6}]; getMatchingIndices(array1, array2); // Returns [0, 2]
Lodash Solution
Use _.forEach to simplify iteration, and optionally _.isEqual for full object matches:
function getMatchingIndicesLodash(array1, array2) { const matchingIndices = []; if (array1.length !== array2.length) return matchingIndices; _.forEach(array1, (item, i) => { // Check only x/y, or use _.isEqual(item, array2[i]) for full object equality if (item.x === array2[i].x && item.y === array2[i].y) { matchingIndices.push(i); } }); return matchingIndices; }
3. 按指定数组顺序排序JSON数据
Suppose your JSON data is an array of objects with a property matching values in array3 (e.g., a chartName field). Here's how to sort the JSON array to match array3's order:
Vanilla JavaScript Solution
Use sort() with a comparator that references the index of each item in array3:
const array3 = ["chart2","chart3","chart1"]; const jsonData = [ {chartName: "chart1", data: [1,2,3]}, {chartName: "chart2", data: [4,5,6]}, {chartName: "chart3", data: [7,8,9]} ]; jsonData.sort((a,b) => { return array3.indexOf(a.chartName) - array3.indexOf(b.chartName); }); // Result: [chart2, chart3, chart1]
Note: Items not in array3 will sort to the front (since indexOf returns -1). Adjust the comparator if you want them at the end (e.g., return Infinity for unmatched values).
Lodash Solution
_.sortBy with a pre-built lookup map boosts performance for large datasets:
// Create a lookup map for O(1) order lookups const orderMap = _.fromPairs(array3.map((val, idx) => [val, idx])); // Sort using the map const sortedJsonData = _.sortBy(jsonData, item => orderMap[item.chartName] || Infinity);
This avoids repeated indexOf calls, making sorting much faster with big arrays.
内容的提问来源于stack exchange,提问作者gautham shetty

