Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
greatInvoker opened this issue Jan 6, 2023 · 4 comments

Comments

@greatInvoker
Copy link

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
Copy link

netRuby commented Feb 21, 2023

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
Copy link

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
Copy link

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
Copy link

brother-forteen commented Jul 2, 2024 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants