第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

如何從javascript中的對(duì)象數(shù)組中獲取最接近的先前id

如何從javascript中的對(duì)象數(shù)組中獲取最接近的先前id

紅顏莎娜 2019-04-24 22:19:44
我有一個(gè)對(duì)象數(shù)組,我想從最近的對(duì)象獲得最接近的前一個(gè)id。我能夠得到最接近的下一個(gè)id,它的工作正常但是以前不能正常工作。它直接取對(duì)象的第一個(gè)id。這是代碼以下。任何人都可以幫助我。JAVASCRIPTconst array = [{id:4}, {id:10}, {id:15}];const findClosesPrevtId = (x) => ( array.find( ({id}) => x <= id ) || {} ).id;const findClosestNextId = (x) => ( array.find( ({id}) => x >= id ) || {} ).id;console.log(findClosesPrevtId(5));console.log(findClosestNextId(11));
查看完整描述

4 回答

?
絕地?zé)o雙

TA貢獻(xiàn)1946條經(jīng)驗(yàn) 獲得超4個(gè)贊

我發(fā)現(xiàn)更容易反轉(zhuǎn)數(shù)組并將比較切換>=為<=:


const findClosestNextId  = (x, arr) => 

  (arr.find ( ({id}) => id >= x) || {} ) .id


const findClosestPrevId  = (x, arr) => 

  (arr .slice(0) .reverse() .find ( ({id}) => id <= x) || {}) .id


const array = [{ id: 4 }, { id: 10 }, { id: 15 }];


console .log (

  findClosestNextId (5,  array), //=> 10

  findClosestNextId (11, array), //=> 15

  findClosestNextId (42, array), //=> undefined


  findClosestPrevId (5,  array), //=> 4

  findClosestPrevId (11, array), //=> 10

  findClosestPrevId (2,  array), //=> undefined

)  

該slice電話有防止這種修改原始數(shù)組。undefined如果沒有找到元素,這將返回。


查看完整回答
反對(duì) 回復(fù) 2019-05-17
?
MMTTMM

TA貢獻(xiàn)1869條經(jīng)驗(yàn) 獲得超4個(gè)贊

我對(duì)您的代碼進(jìn)行了一些更改,現(xiàn)在應(yīng)該可以正常工作了??匆豢?。


    const array = [{id:3}, {id:4}, {id:10}, {id:15}];

    // you should order the list by id before you try to search, this incase you have not orginized list.

    // filter the list first and get the prev id to 5 

    // you should get 3 and 4 then 

    // slice(-1) to get the last element of the array which should be 4

    const findClosesPrevtId = (x) =>

    (array.filter(({id}) => id <= x ).slice(-1)[0] || {}).id;

    const findClosestNextId = (x) => 

    (array.filter(({id}) => id >= x )[0] || {}).id;


    console.log("Prev to 5:"+ findClosesPrevtId(5));

    console.log("Next to 11:" +findClosestNextId(11));


查看完整回答
反對(duì) 回復(fù) 2019-05-17
  • 4 回答
  • 0 關(guān)注
  • 593 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)