Daily-Interview-Question icon indicating copy to clipboard operation
Daily-Interview-Question copied to clipboard

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

Open greatInvoker opened this issue 2 years ago • 4 comments

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));

greatInvoker avatar Jan 06 '23 10:01 greatInvoker

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})

netRuby avatar Feb 21 '23 02:02 netRuby

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;
}

Dylan0916 avatar Aug 23 '23 12:08 Dylan0916

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

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

chennlang avatar Jul 02 '24 10:07 chennlang

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

brother-forteen avatar Jul 02 '24 10:07 brother-forteen