Troubling removing string in Javascript array - javascript

I am having trouble understanding what to do next. The following code removes all the duplicate numbers but I also need to remove the strings without converting them to numbers. I'm not sure how to proceed...
var arr = [ 10, 44, 55 ,66 , 77 , 55 , 44 , 3 , 3 , 3 , 4 , 5 , 6 , 54 , "henry", "33", "£", "66"]
var max = {};
function biggerThanMax(arr){
return arr.filter(function(item,index){
return arr.indexOf(item) >= index;
});
};
biggerThanMax(arr)

use typeof x to check the type of variable x

You want to use typeof
var arr = [
10, 44, 55, 66, 77, 55, 44,
3, 3, 3, 4, 5, 6, 54,
"henry", "33", "£", "66"
]
var max = {};
function biggerThanMax(arr) {
return arr.filter(function(item, index) {
return typeof item == 'number' && arr.indexOf(item) >= index;
});
};
console.log(biggerThanMax(arr))
You also have a couple of typos (which are likely a typo in your example)
Unclosed array
Missing biggerThanMax opening bracket.

Related

Prevent arrray.map returning undefined when condition/callback is not met [duplicate]

This question already has answers here:
How to skip over an element in .map()?
(18 answers)
Map and filter an array at the same time
(16 answers)
Closed 1 year ago.
I was writing some code and something puzzled me. I have an array of numbers called alarmsList. Now I wish to iterate through this list and if a value is higher than 60 for example I want to create a new object array (collection) where we store the high value and it's index from the original array. So take the following code
const alarmsList = [1, 61, 77, 4, 5, 6, 7, 8, 85, 4, 3, 55];
const highAlarmsList = alarmsList.map((item, index) => {
if(item > 60) {
return ({ value: item, index })
}
});
console.log(highAlarmsList)
The console.log outputs the following
[
undefined,
{
"value": 61,
"index": 1
},
{
"value": 77,
"index": 2
},
undefined,
undefined,
undefined,
undefined,
undefined,
{
"value": 85,
"index": 8
},
undefined,
undefined,
undefined
]
This output is what I require but how do I prevent the undefined values being returned? I thought about using array.filter but that doesn't seem appropriate? Should I use a different array method? I don't want to use a for loop and push to a new array unless that is the best/only way to achieve the new array without the undefined values being returned.
You can use Array.filter() to removing the undefined values by using Boolean as the predicate:
const alarmsList = [1, 61, 77, 4, 5, 6, 7, 8, 85, 4, 3, 55];
const highAlarmsList = alarmsList.map((item, index) => {
if(item > 60) {
return ({ value: item, index })
}
}).filter(Boolean);
console.log(highAlarmsList)
You can use Array.flatMap() and return empty arrays instead of undefined, but that might effect performance for huge arrays:
const alarmsList = [1, 61, 77, 4, 5, 6, 7, 8, 85, 4, 3, 55];
const highAlarmsList = alarmsList.flatMap((item, index) =>
item > 60 ? { value: item, index } : []
);
console.log(highAlarmsList)
map creates a new array by running the callback on every element of the array. If the condition does not satisfy it will return undefined or null. So it not possible to skip the element from the output.
Alternatively you can ue reduce or filter
const alarmsList = [1, 61, 77, 4, 5, 6, 7, 8, 85, 4, 3, 55];
const highAlarmsList = alarmsList.reduce((acc, item, index) => {
item > 60 && acc.push({
value: item,
index
})
return acc;
}, [])
console.log(highAlarmsList)

How can I get the largest number value along with the username from this array?

Im trying to get the user & value with the highest number from this array but have had no luck in my searches. I'm starting to wonder if my array is poorly written.
{
"radtech2": 1,
"conorlarkin4": 25,
"jdon2001": 15,
"nobel_veo": 101,
"frapoden": 1,
"duckyboy17": 31,
"faeded": 30,
"jimbob20001": 17,
"leb0wski": 15,
"3cavalry": 2,
"hardoak22": 25,
"deep_slide": 10000,
"sillywil": 7
}
const users = {
"radtech2": 1,
"conorlarkin4": 25,
"jdon2001": 15,
"nobel_veo": 101,
"frapoden": 1,
"duckyboy17": 31,
"faeded": 30,
"jimbob20001": 17,
"leb0wski": 15,
"3cavalry": 2,
"hardoak22": 25,
"deep_slide": 10000,
"sillywil": 7
};
const highestUser = users => Object.keys(users).reduce(
(highest, current) => highest.val > users[current] ? highest : { user: current, val: users[current] },
{ user: undefined, val: -Infinity }
).user;
console.log(highestUser(users));
Use keys() and entries() methods to search your JSON object. Save largest value into e.g. const largest and then find out which key belongs to this value.
Let me try to squeeze it into a one-liner approach using Object.keys() and Array.reduce().
const users = {
"radtech2": 1,
"conorlarkin4": 25,
"jdon2001": 15,
"nobel_veo": 101,
"frapoden": 1,
"duckyboy17": 31,
"faeded": 30,
"jimbob20001": 17,
"leb0wski": 15,
"3cavalry": 2,
"hardoak22": 25,
"deep_slide": 10000,
"sillywil": 7
};
const res = Object.keys(users).reduce((a, b) => users[a] > users[b] ? a : b);
console.log(res);
How the above code works is that I get the array of keys from the users object, and I use reduce to get the highest possible value and return the corresponding property from the array obtained from Object.keys().
What you show in your question is an Object, not an Array; however, it does need to be turned into an array in order to work with it.
You can do that with Object.entries(), which will return an array of all the key/value pairs in the object.
Then you can use Array.reduce() to extract the one with the largest value.
const data = {
"radtech2": 1,
"conorlarkin4": 25,
"jdon2001": 15,
"nobel_veo": 101,
"frapoden": 1,
"duckyboy17": 31,
"faeded": 30,
"jimbob20001": 17,
"leb0wski": 15,
"3cavalry": 2,
"hardoak22": 25,
"deep_slide": 10000,
"sillywil": 7
}
let winner = Object.entries(data).reduce((a, b) => (a[1] > b[1]) ? a : b)
console.log(winner)

Trouble at comparing arrays

I have 'shared.checkedFacility' scope array in controller which read something like:
[14, 49, 93, 122, 44, 40, 88, 83, 65, 9, 38, 28, 8, 53, 125, 155]
and i am dynamically generating two dimensional array in front end where, for example, single dimentional array from 'shared.facilities[$parent.$index]' read like
{"0":56,"1":13,"2":49,"3":3,"4":11,"5":7,"6":19,"7":4,"8":9,"9":131,"10":21}
Now i am comparing this two array in ng-show argument like
containsAny(shared.checkedFacility,shared.facilities[$index])
Where as function defination is like
function containsAny(source, target) {
console.log("contains called");
var result = source.filter(function(item) {
return target.indexOf(item) > -1
});
return (result.length > 0);
}
But some how this function is not returning true or false, how to make it work?
Please rescue me since i am afresh here in Angular or in Javascript Env straight from PHP.
You can use Object.keys(), .map() to create an array from shared.facilities[$parent.$index]
// `shared.checkedFacility`
var checkedFacility = [14
, 49
, 93
, 122
, 44
, 40
, 88
, 83
, 65
, 9
, 38
, 28
, 8
, 53
, 125
, 155
];
// shared.facilities[$parent.$index]
var facilities = {
"0": 56,
"1": 13,
"2": 49,
"3": 3,
"4": 11,
"5": 7,
"6": 19,
"7": 4,
"8": 9,
"9": 131,
"10": 21
};
// create an array having values contained in `facilities`
var arr = Object.keys(facilities).map(function(prop, index) {
return facilities[prop]
});
console.log(arr)
function containsAny(source, target) {
console.log("contains called");
var result = source.filter(function(item) {
return target.indexOf(item) > -1
});
return (result.length > 0);
}
// pass `arr` as second parameter to `containsAny`
var res = containsAny(checkedFacility, arr);
console.log(res)
Your function is failing on:
target.indexOf(item)
because target in your example is an Object and not an Array, so you can't call indexOf function.
So you are most likely getting:
Uncaught TypeError: target.indexOf is not a function
To solve that, you have to pass an Array as target instead of passing an Object.

Pairing multiple javascript arrays

I'm trying to solve a problem I have with multiple javascript arrays.
So basically the result I want is to match the arrays of a dropdown box with other values from other arrays that I will display.
The arrays contain different values, but the order is the most important thing
var array1 = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22];
var array2 = [30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50];
var array3 = [36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56];
Let's say the user selects number 4, then I need to somehow select 32 in array2 and 38 in array3.
Any suggestions are gladly accepted, Thanks!
Get the index from the first array, with Array.prototype.indexOf
var index = array1.indexOf(4);
Get the values from other arrays with that index, like this
console.log(array2[index], array3[index]);
Note: If the value being searched is not found in the array, indexOf will not fail with an error but it will simply return -1. So, you might want to check before using that to access the elements from other arrays, like this
var index = array1.indexOf(4);
if (index !== -1) {
console.log(array2[index], array3[index]);
} else {
console.log("Invalid element selected");
}
Any time you have multiple parallel arrays, you should really consider refactoring it into a single array of objects. That way you never have to worry about keeping them synched. For example:
var myArray = [ { val1: 2, val2: 30, val3: 36 }, { val1: 4, val2: 32, val3: 38 }, ...];
Now to find the value for 4 you can simply do something like (although a simple for loop might be more efficient since you know there is only ever one result):
var myValues = myArray.filter(function(item) { return item.val1 === 4 });
And then access myValues[0].val2 and myValues[0].val3.
Or, if you are always looking up by the first value, you can use that as your key for an object that maps to your other two values. Something like:
var myArray = { 2: { val2: 30, val3: 36 }, 4: { val2: 32, val3: 38 },...};
Now if you want the other two values for 4 you can simply:
var value2 = myArray[4];
var value3 = myArray[4];
Assuming those are not only arrays and values, but you have actual <select> dropdown boxes:
Accessing the selected value is not only possible by using select1.value, but also by using select1.options[select1.selectedIndex].value. That.selectedIndex is what we are interested in, and you can use that equivalently on the option collections of the other two dropdowns, or the arrays with their values:
select2.options[select1.selectedIndex].value
array2[select1.selectedIndex]
select3.options[select1.selectedIndex].value
array3[select1.selectedIndex]
If you access them via the options collection you will need to make sure that one option is actually selected (select1.selectedIndex != -1), otherwise you'd get an exception.
Do it like this,
var valueFromSelect = 4;
var array1 = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22];
var array2 = [30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50];
var array3 = [36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56];
for(var i = 0; i < array1.length; i++){
if(valueFromSelect == array1[i]){
console.log(array2[i], array3[i]);
break;
}
}
I suggest you don't use indexOf, it's not compatible with IE < 9 read more about that here indexOf MDN

Dynamically fill multidimensional array with arrays

I've been doing some research and am not getting anywhere. I have a situation where I need an array to contain a possibly variable number of arrays. Based on the example below, do you have any ideas?
var masterArray = [];
function PrepData(inVal) {
var amt = inVal.split("|");
for (var i = 0; i < amt.length; i++) {
// !!!Trouble area!!!
masterArray[i].push = amt[i];
};
}
What I'm doing is feeding 12 months' worth of data into this function, so PrepData runs 12 times each time I activate the calling function. The variable inVal can contain something like "9|9|0" or "9|123|470|1500|13". What I'm looking to do is split the incoming value on the pipe and store the results in amt. Then I want to feed each value from amt into individual arrays within masterArray. The good news is that inVal's length is constant once the first value is in, so if the first of 12 iterations splits into 3 pieces, the other 11 will also. To lay it out, here's what I would expect a typical run to produce given this input:
Oct: "1|2|1300"
Nov: "1|3|1400"
Dec: "2|5|1450"
Jan: "3|6|1900"
Feb: "4|8|2015"
Mar: "4|8|2020"
Apr: "19|38|3200"
May: "30|42|3500"
Jun: "32|50|5000"
Jul: "48|72|6300"
Aug: "50|150|7500"
Sep: "80|173|9000"
Once all twelve run through PrepData, I should have an array that contains this:
masterArray[0] == {1, 1, 2, 3, 4, 4, 19, 30, 32, 48, 50, 80} // All the numbers from the first section
masterArray[1] == {2, 3, 5, 6, 8, 8, 38, 42, 50, 72, 150, 173} // All the numbers from the second section
masterArray[2] == {1300, 1400, 1450, 1900, 2015, 2020, 3200, 3500, 5000, 6300, 7500, 9000} // All the numbers from the third section
If each month contained a string with 5 sections, then masterArray would need to be able to go from [0] to [4], and so on. The trouble area above isn't working, so I'm obviously missing something, but don't know what that might be.
Here is the updated code
var masterArray = [];
function PrepData(inVal){
var amt = inVal.split("|");
for (i in amt) {
if(typeof masterArray[i] == 'undefined'){
masterArray[i] = [];
}
masterArray[i].push(amt[i]);
}
}
There is a need to check first if an array is defined in each index in masterArray. If it's not defined then you need to initialize it to a blank array. Then you can push the splited value and you get the same result
masterArray[0] == {1, 1, 2, 3, 4, 4, 19, 30, 32, 48, 50, 80}
masterArray[1] == {2, 3, 5, 6, 8, 8, 38, 42, 50, 72, 150, 173}
masterArray[2] == {1300, 1400, 1450, 1900, 2015, 2020, 3200, 3500, 5000, 6300, 7500, 9000}
Here is a demo in js fiddle

Categories