如何在ID非连续的无序对象数组中按ID属性获取上一个元素
实现逻辑
你需要的是找到所有小于当前ID的ID中数值最大的对应元素,不需要对当前ID做固定数值的减法,就能自动适配ID不连续的场景,同时兼容数组任意位置的查询,第一个元素查询前项时会返回null。
方案1:通用版(适配任意顺序的数组)
不需要数组提前排序,ID乱序也能正常运行,适合数组元素会动态增删、顺序不固定的场景:
function getPrevItem(currentId, itemArray) { // 筛选所有ID小于当前ID的元素 const smallerIdItems = itemArray.filter(item => item.id < currentId); // 没有更小的ID,说明是首个元素,返回null if (smallerIdItems.length === 0) return null; // 取筛选结果中ID最大的元素即为目标前项 return smallerIdItems.reduce((prev, curr) => curr.id > prev.id ? curr : prev); } // 测试示例(使用你提供的数组) const productArray = [ {"id":1,"nombre":"DITTO-X2 Looper","precio":"10999","img":"DITTO-X2.png","categoria":"pedales","sub_categoria":"loop_pedal","descripcion":"looper","marca":"ditto"}, {"id":2,"nombre":"Guitarra Taylor 562ce","precio":"73999","img":"guitarra562ce.png","categoria":"cuerdas","sub_categoria":"guitarra_acustica","marca":"taylor","descripcion":"Taylor’s Grand Concert 12-strings reaffirm Taylor’s heritage of easy-playing double course instruments thanks to a lap-friendly body size, a 12-fret neck, and a 24-7/8-inch scale length. The slinky handfeel makes fretting and bending strings easier, the neck and body are comfortably balanced, and the compact body produces a clear 12-string voice. The hardwood mahogany top adds just enough compression to the attack to smooth out the response, bringing an appealing consistency across the tonal spectrum, while still capturing the beautiful octave shimmer. V-Class bracing adds another dimension of musicality, improving volume and sustain so that notes and chords bloom and expand as they resonate. It makes a great 12-string choice for tracking in a studio, and behaves well with other instruments in a live setting. Refined aesthetic touches include a shaded edgeburst body and neck, faux tortoise shell binding, a rosette of faux tortoise shell and grained ivoroid, and a grained ivoroid Century fretboard inlay."}, {"id":4,"nombre":"BC-1x","precio":"38000","img":"1633645625329_img_.png","categoria":"pedales","sub_categoria":"bass_pedal","descripcion":"Pedal","marca":"boss"}, {"id":6,"nombre":"VE-500","precio":"30000","img":"1634188562527_img_.jpg","sub_categoria":"vocal_pedal","marca":"BOSS","descripcion":"If you’re like most guitarists, you spend a lot of time choosing the right amps and pedals to craft your own personalized sound. But if you sing in your band as well, it hasn’t always been so easy to give your vocal sounds that same attention to detail—until now. The advanced VE-500 Vocal Performer provides everything you need to achieve impressive vocal harmonies and effects on stage, and all in streamlined stompbox that integrates seamlessly with the regular guitar effects on your pedalboard."} ]; // 测试输出 console.log(getPrevItem(6, productArray)); // 返回id为4的BC-1x对象 console.log(getPrevItem(2, productArray)); // 返回id为1的DITTO-X2 Looper对象 console.log(getPrevItem(1, productArray)); // 返回null
方案2:优化版(仅适用于已按ID升序排序的数组)
如果你的数组和示例一样固定按ID升序排列,没有乱序情况,可以用索引查找的方式获得更高性能,尤其适合数组长度很大的场景:
function getPrevItemSorted(currentId, sortedArray) { // 查找当前元素的索引 const currentIndex = sortedArray.findIndex(item => item.id === currentId); // 找不到元素或者已经是首个元素,返回null if (currentIndex <= 0) return null; // 直接返回前一个索引位置的元素 return sortedArray[currentIndex - 1]; } // 测试输出 console.log(getPrevItemSorted(6, productArray)); // 返回id为4的BC-1x对象
内容的提问来源于stack exchange,提问作者TadeoGavensky
相关产品推荐
相关产品推荐

