-2

I have the following array

var arr = ['1234','23C','456','356778', '56']

I want to remove array elements which are less than 3 characters and greater than 4 characters. The final result should be as follows

arr = ['1234', '23C', '456'];  //only 3 and 4 digits in the array. 

Secondly, I want to do the following. if 'arr' has elements longer than 3 characters, I need to clip of by removing the last digit. The final 'data' array should look like this.

arr = ['123', '23C', '456'];
Adu Rao
  • 101
  • 2
  • 4
  • 10
  • check http://stackoverflow.com/questions/1187518/javascript-array-difference – AlecTMH Nov 30 '16 at 16:38
  • alecTMH- i have a different conditon here and i am not able to figure out from that link. – Adu Rao Nov 30 '16 at 16:46
  • Are you trying to do two different things to two separate arrays? Or are you trying to filter the array to 3s and 4s, and then change the size of the values with 4 or more? – KevBot Nov 30 '16 at 16:50
  • KevBot. Yes. Filter array to 3s and 4s from 3s,4s,5s,2s and then change the 4s to all 3s.... – Adu Rao Nov 30 '16 at 16:53
  • Filter the array with a predicate that checks the number is greater than 99 and less than 10000 – Gruff Bunny Nov 30 '16 at 16:56
  • @GruffBunny- i might have alphanumeric in some cases... for e.g. '1234D', 'ER3' etc... – Adu Rao Nov 30 '16 at 16:59
  • 4
    *I tried searching online and could not find anything related to this.* Well, of course you couldn't. No one else has this problem. But you could find thousands of references about how to filter arrays, or how to transform the items in arrays. –  Nov 30 '16 at 17:16

6 Answers6

1

For the first part, you can just use filter to filter out numbers that aren't composed of 3 digits.

var arr = [1234, 234, 456, 356778, 56];
var result = arr.filter(function(num) {
  return num < 1000 && num >= 100;
});

console.log(result);

For the second part, you can use map. Just convert the number to a string. If the length of it is greater than 3, take the substring composed of the first 3 elements of the string, then convert back to a number.

var data = [1234, 123, 4567, 3333];
var result = data.map(function(num) {
  num = num.toString().substring(0, 3);
  return parseInt(num);
});

console.log(result);
Gavin
  • 4,365
  • 1
  • 18
  • 27
0

All You want is Array.filter and Array.map, and converting String to Number

var arr = [1234,234,456,356778, 56]

var newArr = arr.filter((num) => {
  // convert number to string
  var str = '' + num
  // if length is 3 or 4 - return true (element will be in newArr)
  return str.length === 3 && str.length === 4 
})

and the second case

var newArr = arr.map((num) => {
  var str = '' + num
  // is str is longer than 3, cut it to length of 3
  if(str.length > 3)
    str = str.substring(0, 3)
  // return str converted to number
  return +str
})
grzesiekgs
  • 463
  • 2
  • 11
  • @grzesiekgs- are you sure of the syntax used in array.filter. i am getting errors... – Adu Rao Nov 30 '16 at 16:58
  • I've written it from memory. It's ES6 syntax You can replace `(arg) =>` with `function(arg)` – grzesiekgs Nov 30 '16 at 17:03
  • @grzesiekgs- can you edit your answer so i can accept it as the correct answer please – Adu Rao Nov 30 '16 at 17:08
  • 1
    Why is the ` if(str.length > 3)` necessary? –  Nov 30 '16 at 17:36
  • 1
    I don't think `str.length === 3 && str.length === 4` is going to work. Did you test this? –  Nov 30 '16 at 17:54
  • @AduRao It would work. String is like an array, it has 'length', which means how many characters is in string. The code which You have accepted as an anserw, is ok, but well it's not optimized. First example is pretty much ok. But I wouldn't use it because You have to hard code minimum and maximum value - which is bad. In second example, there is toString() and parseInt() methods, which are indeed very verbose, but it's not the fastest way of converting (You can look for some benchmarks). Also - new string with length of 3 is always created, even if it is not necessary. – grzesiekgs Dec 01 '16 at 11:43
0

To handle if a number is 3 or 4 digits, check if each number is in the range 100 <= num < 10000

  let result = arr.filter(function(val) {
    // is a 3 or 4 digit number
    return 100 >= val && num < 10000;
  });

To clip the four digits to 3 digits, we can divide all four digit numbers by 10 and convert them to an integer

  let clippedResult = result.map(function(val) {
    return val >= 1000 ? Math.floor(val / 10) : val
  });
megawac
  • 10,953
  • 5
  • 40
  • 61
0
function filterArray(arr,lowDigits,highDigits){
    var newArr=[];
    for(i=0;i<arr.length;i++){
         val=arr[i];
         length=val.length;
         if(length>=lowDigits&&length<=highDigits){
          if(length>lowDigits){
          val=val.substring(0,lowDigits);
          }
          newArr.push(val);
         }
     }
     return newArr;
}

var arr = ['1234','234','456','356778','56'];
arr=filterArray(arr,3,4);
console.log(arr);
sigil
  • 9,370
  • 40
  • 119
  • 199
  • Yes, because it treats them as strings. – sigil Nov 30 '16 at 17:25
  • @sigil- this doesnot work properly. if i do arr = filterArray(arr, 6,7)... i get this result ---> ["004561", "045449", "00456"]. i.e. it shows 5 character value too in the output. '00456' – Adu Rao Nov 30 '16 at 19:15
  • @AduRao What was the input array when you tested? I just ran `["004561", "045449", "00456"]` with `filterArray(arr,6,7)` and got back `["004561", "045449"]` as expected. – sigil Nov 30 '16 at 21:49
0

This solution converts the input array to a string of the form 1234,23C,456,356778,56, then finds the wanted elements using regexp.

var arr = ['1234','23C','456','356778', '56'];

console.log(String(arr).match(/\b\w{3}(?=\w?\b)/g));

In English:

Find all the substrings which start with a word boundary (\b, which will be after a comma, or the beginning of the string), then have three alphanumeric characters, and which looking ahead ((?=) may (?) have one additional character before the next word boundary (comma or end of string).

And yes, this will work with string elements, as long as the strings are composed of alphanumerics (in other words, things which won't break the word break (\b) logic.

-1
 let isValidElement = updated_ImportDetails.ImportData.filter(function (num) {
                    // is a 3 or 4 digit number
                    return num.length > 2 && num.length <4 ;
                });




                var result = isValidElement.map(function (num) {
                    num = num.substring(0, 3);
                    return num;
                });

                result = result.filter(function (elem, index, self) {
                    return index == self.indexOf(elem);
                })    //removes duplicates from the array

This worked for me.

Adu Rao
  • 101
  • 2
  • 4
  • 10