Advanced-Frontend / Daily-Interview-Question

我是依扬(木易杨),公众号「高级前端进阶」作者,每天搞定一道前端大厂面试题,祝大家天天进步,一年后会看到不一样的自己。
https://muyiy.cn/question/
27.4k stars 3.29k forks source link

第 161 题:用最精炼的代码实现数组非零非负最小值 index #582

Open greatInvoker opened 1 year ago

greatInvoker commented 1 year ago
const arr = [10, 21, 0, -7, 35, 7, 9, 23, 18];

function getIndex(arr) {
    let min = Infinity;
    arr.forEach((v) => {
        v > 0 && v < min && (min = v);
    });
    return arr.indexOf(min);
}

console.log(getIndex(arr));
netRuby commented 1 year ago

const arr = [10, 21, 0, -7, 35, 7, 9, 23, 18];

arr.reduce((pre,cur,index)=>{ return cur>0&cur<pre.val ? {i:index,val:cur} : pre },{i:-1,val:Infinity})

Dylan0916 commented 1 year ago
const ary = [10, 21, 0, -7, 35, 7, 9, 23, 18];

function getIndex(ary) {
  const result = ary.reduce(
    (acc, cur, index) =>
      acc.value > cur && cur > 0 ? { value: cur, index } : acc,
    { value: Infinity, index: -1 }
  );

  return result.index;
}
chennlang commented 3 months ago

const arr = [10, 21, 0, -7, 35, 7, 9, 23, 18];

const min = arr..sort((a,b) => a-b).filter(n => n > 0)[0]

brother-forteen commented 3 months ago

这是来自QQ邮箱的假期自动回复邮件。 您好,您的邮件我已经收到,我会尽快给您回复,谢谢。