2

Here, I am trying to find index of negative numbers in an array in JavaScript? Please help?

 Case1: var arr=[1,-5,-6,7,8,9,10,-14,6,-7];  

/*---------logic to find index of negative numbers in an array?*/

 console.log();

 Case2: var arr=["1","-3","5","-9","-10","11"]
 /*------logic to find index of negative numbers from array of strings(arr)?*/

console.log();

 Case3: var arr=["1","-3M" ,"2P","-8Q","-10.8%","-$8.00M"]

 /*----------How to find index of "-" in an array of strings----------*/

    console.log()
2
  • 1
    Did you try anything ? What approach did you try that did not work ? Commented Jul 22, 2017 at 17:10
  • The indexes of all negatives, or the index of any negative? What do you want to do with them once found? Commented Jul 22, 2017 at 17:12

7 Answers 7

6

You could map the indices with the index only for negative numbers and then filter only the ones with valid indices.

var array = [1, -5, -6, 7, 8, 9, 10, -14, 6, -7],
    indices = array
        .map((a, i) => a < 0 ? i : -1)
        .filter(a => a !== -1);

console.log(indices);

Nearly the same for strings and a check if the first character is -.

var array = ["1", "-3M", "2P", "-8Q", "-10.8%", "-$8.00M"],
    indices = array
        .map((a, i) => a[0] === '-' ? i : -1)
        .filter(a => a !== -1);

console.log(indices);

And now a solution for numbers or strings with toString method.

var array = ["1", -3, "2P", "-8Q", "-10.8%", "-$8.00M"],
    indices = array
        .map((a, i) => a.toString()[0] === '-' ? i : -1)
        .filter(a => a !== -1);

console.log(indices);

Sign up to request clarification or add additional context in comments.

15 Comments

I fail to see why using map to return an array that then has to be filtered is somehow better than just getting only the desired values in the first place.
@ScottMarcus, i read find index of negative numbers numbers is her plural, so not just the first ..., but if just the first, the a loop with early exit would do (or some).
Thanks, Please help for case2 and case3 scenario.
Understood. My point still stands. You can get all the indexes of all the negatives with just forEach().
@ScottMarcus: I just personally find clever the usage of .map and .filter (check my fiddle as well), and the fact that she is using .toString()[0], along with using the map key. Moreover, it's a sort of inline solution, which I always prefer over a longer solution which requires (eventually) to re-declare a new array that needs to be returned. It's just matter of preferences anyway, I'm not saying that using a foreach loop is not correct, I just say that I prefer the approach that Nina used. Besides, the solution can be unified in a single line (my fiddle works with every case).
|
1

Use the Array.forEach() looping method and regular expressions.

Here's a single function that will handle all 3 of your scenarios.

var arr = [1,-5,-6,7,8,9,10,-14,6,-7];
var arr2 = ["1","-3","5","-9","-10","11"];
var arr3 = ["1","-3M" ,"2P","-8Q","-10.8%","-$8.00M"];

function getNegatives(arr){
  var results =[];
  arr.forEach(function(item, index){
    // If item is a string, remove all non-numeric characters and then convert to a number
    var newItem = (typeof item === "string") ? parseFloat(item.replace(/[^-\d\.]/g,'')) : item;
    if(newItem < 0){ results.push(index); }
  });
  console.log(results);
}

getNegatives(arr);
getNegatives(arr2);
getNegatives(arr3);

2 Comments

Thanks, Please help for case2 and case3.
@ManzerAhmad See my updated answer for a single function that handles all of your scenarios.
0

You can do it using for loop and if condition.

var arr = [1,-5,-6,7,8,9,10,-14,6,-7];
var negativeNumbersIndexs = [];
var i; // for the loop
for (i = 0; i < arr.length; i += 1) {
    if (arr[i] < 0){
        negativeNumbersIndexs.push(i)
    }
}

console.log(negativeNumbersIndexs);

Comments

0

You can use for like this.

var i;
for(i = 0; i < arr.length; i++) {
  if(arr[i] < 0) {
    console.log("Index " + i);
  }
} 

Comments

0

Try this code.

var arr = [1,-5,-6,7,8,9,10,-14,6,-7];
for(var i = 0; i < arr.length; i++) {
    if(arr[i] < 0) {
      console.log(arr[i] +  " is at index: " +  i);
    }
}

3 Comments

There are two other just about identical answers that were posted prior to yours. What value does your answer provide?
@Scott Marcus I help this link to answered that problem. stackoverflow.com/questions/40227381/…
Your answer didn't include that link. It just recreated the same code that two other answers that were already here have.
0

var arr=[1,-5,-6,7,8,9,10,-14,6,-7];
var res = arr.reduce( function(out, a, i) {
   return a<0 ? out.concat([i]) : out;
},[]);
console.log( res );

1 Comment

Yup, there was at typo
0

Case1: finding index of negative numbers in an array of numbers:

for(var i=0; i < arr.length; i++){
    if(arr[i] < 0){
       console.log(i);
    }
}

Case2: finding index of negative numbers in an array of strings:

for(var i=0; i < arr.length; i++){
    if(Number(arr[i]) < 0){
       console.log(i);
    }
}

Case3: finding index of negative "-" in an array of strings:

for(var i=0; i < arr.length; i++){
    if(arr[i].charAt(0) === "-"){
       console.log(i);
    }
}

Note: you can use solution of case3 in case2 also it will work fine in both cases.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.