Index of the largest float in the array - javascript

How can I get the index of the largest element in the array of floats?
[0.000004619778924223204, 0.8323721355744392, 0.9573732678543363, 1.2476616422122455e-14, 2.846605856163335e-8]
Once I get this index, I then want to get the value of another array at this index.
Let's call the second array:
['a', 'b', 'c', 'd', 'e']
When I ran the following, I got 'b' instead of 'c'.
I iterated through the first array and made a map of the floats to the strings. Then I got the string at the the first element of the first array ( array of floats ) sorted.
//aInput in the array of floats.
var emObj={};
for(var i=0; i<aInput.length; i++){
emObj[aInput[i]]=['a', 'b', 'c', 'd', 'e'][i];
}
return emObj[aInput.sort()[0]];
I also tried a method where I iterated through the array of floats and stored the largest value in a variable. Then I'd do something like this:
return ['a', 'b', 'c', 'd', 'e'][aInput.indexOf(largestFloat)];
But neither of these worked. Always returning the wrong string.

I'd suggest using Math.max() and indexOf()
var maxNum = Math.max.apply(null, aInput);
var index = aInput.indexOf(maxNum);
return ['a', 'b', 'c', 'd', 'e'][index];

An approach using Array.prototype.reduce()
This allows for arbitrary complexity in the reduce logic.
First, set up some data:
var data = [0.000004619778924223204, 0.8323721355744392, 0.9573732678543363, 1.2476616422122455e-14, 2.846605856163335e-8];
var reference = ['a', 'b', 'c', 'd', 'e'];
Then, find the value and index of the maximum value in the array.
var result = data.reduce(function (previousValue, currentValue, index, array) {
if(previousValue.value > currentValue) {
return previousValue;
} else {
return {value: currentValue, index: index};
}
})
console.log(reference[result.index]);
Alternatively you could find the referenced value directly like this.
var result = data.reduce(function (previousValue, currentValue, index, array) {
if(previousValue.value1 > currentValue) {
return previousValue;
} else {
return {value1: currentValue, value2: reference[index]};
}
})
console.log(result);
This outputs Object {value1: 0.9573732678543363, value2: "c"}

Related

JS bracket notation clarification

Thanks in advance. I have a concept question in JavaScript;
function rand(x,z)
{ return x + Math.floor((z-x+1)*Math.random()); }
function getLetter()
{ return ['a', 'b', 'c', 'd', 'e', 'f'][rand(0,5)]; }
console.log(getLetter()); // f // a // c .....
I'm having trouble understanding how the getLetter() function logs a randomly selected letter just by returning two arrays. If I reverse the the array order it is logged in console as undefined.
Ultimately, I haven't seen this syntax before and it threw me off guard. Does the getLetter() function behave the same way as a .map() and .filter() approach?
See the returned value as a row randomly picked up from an array:
var letters = ['a', 'b', 'c', 'd', 'e', 'f']
like
Array (
0 => 'a',
1 => 'b',
2 => 'c',
3 => 'd',
4 => 'e',
5 => 'f'
)
The [rand(0,5)] is the row selector (random number from the first row id to the last row id, which are from 0 to 5).
Your getLetter() function can be seen as:
function getLetter() {
var letters = ['a', 'b', 'c', 'd', 'e', 'f'];
return letters[rand(0,5)];
}
rand returns a random integer between the two numbers passed in (inclusively-- 0 and 5 are valid returns, as are any integer in between).
getLetter leverages it as a means to get a random index in an array of letter that contains six letters. So this:
['a', 'b', 'c', 'd', 'e', 'f'][rand(0,5)]
Calls rand. And let's pretend it returns 2. So then we have:
['a', 'b', 'c', 'd', 'e', 'f'][2]
Which is the third item in the array, so 'c' is returned.
There are no two arrays. There is one array and using bracket notation to reference an index in the array. Below is what the code basically does:
function getLetter() {
var options = ['a', 'b', 'c', 'd', 'e', 'f'], //defined array
randomNumber = rand(0,5), //generate random number
selection = options[randomNumber]; //reference index with the random number
return selection; //return the value
}
Your getLetter function is actually returning an element of a single dimension array. Basically it is creating an array of 6 characters (a thru f) and then returns the one pointed to by the index generated by the rand function.
The reverse (return [rand(0,5)]['a', 'b', 'c', 'd', 'e', 'f'];) doesn't work because the array object generated in that case is a one element array (which contains a random number between 0 and 5).
The rand function is just returning a number in the inclusive interval [0, 5].
getLetter will just return the charcater in the ['a', 'b', 'c', 'd', 'e', 'f'] at the random character genered by rand.
['a', 'b', 'c', 'd', 'e', 'f'] is an array, expression[x] is on the other hand getting the element at the x index in the expression array starting from zero.

Push and remove duplicates of array

I have an array (or Set?) of arr = ['a', 'b', 'c'] and I want to add d to it, which could be done with arr.push('d').
But I only want unique values in the array, and I want the latest values added to be in the front of the array.
So if I first add d the array should become ['d', 'a', 'b', 'c'] and if I now add b the array should become ['b', 'd', 'a', 'c'] etc.
Should it be something like
function addElement(arr, element) {
if (arr.includes(element)) {
arr.splice(arr.indexOf(element, 1));
}
arr.unshift(element);
}
I guess this could be done with Sets, since sets can only contain unique values.
You could use a Set and delete the item in advance and add it then. To get the wanted order, you need to reverse the rendered array.
function addToSet(v, set) {
set.delete(v);
set.add(v);
}
var set = new Set;
addToSet('d', set);
addToSet('c', set);
addToSet('b', set),
addToSet('a', set);
addToSet('d', set);
console.log([...set].reverse());
var val = 'c';
var arr = ['a','b'];
if($.inArray( val, arr ) ==-1){
// value dosend exit
arr.unshift(val);
} else {
console.log('value already there')
}
console.log(arr);
$.inArray() work similar to indexOf() method. It searches the element in an array, if it’s found then it return it’s index.
http://webrewrite.com/check-value-exist-array-javascriptjquery/
your function works just you have to adjust with a small fix
arr.splice(arr.indexOf(element),1);
var arr = ['a', 'b', 'c'] ;
function addElement(arr, element) {
if (arr.includes(element)) {
arr.splice(arr.indexOf(element),1);
}
arr.unshift(element);
}
addElement(arr,'d');
addElement(arr,'b');
console.log(arr);
Especially for those who don't like .unshift() performance This would be another way of doing this job;
function funky(a,e){
var ix = a.indexOf(e);
return (~ix ? a.splice(ix,0,...a.splice(0,ix))
: a.splice(0,0,e),a);
}
var a = ['d', 'a', 'b', 'c'];
console.log(funky(a,'z'));
console.log(funky(a,'d'));
console.log(funky(a,'c'));
console.log(funky(a,'f'));

Lodash method to check whether all elements in an array are in another array

I have 2 arrays of string. I want to make sure all elements of the second array are in the first. I use Lodash/Underscore for things like this. Its easy when checking if one astring is in an array:
var arr1 = ['a', 'b', 'c', 'd'];
_.includes(arr1, 'b');
// => true
But when its an array, I cant see a current method to do it. What I've done is:
var arr1 = ['a', 'b', 'c', 'd'];
var arr2 = ['a', 'b', 'x'];
var intersection = _.intersection(arr1, arr2);
console.log('intersection is ', intersection);
if (intersection.length < arr2.length) {
console.log('no');
} else {
console.log('yes');
}
Fiddle is here. But its rather long-winded. Is there a built in Lodash method?
You could use _.xor for a symmetric difference and take the length as check. If length === 0, the both arrays contains the same elements.
var arr1 = ['a', 'b', 'c', 'd'],
arr2 = ['a', 'b', 'x'];
console.log(_.xor(arr2, arr1));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

How to get the even and odd entries from an array with Ramda

I have the following:
var isEven = function (n) { return n % 2 === 0; }
var isOdd = function (n) { return n % 2 !== 0; }
var indexedList = function(fn, list) {
var array = [];
for (var i = 0; i < list.length; i++) {
if (fn(i)) {
array.push(list[i]);
}
}
return array;
}
Is there a Ramda equivalent of IndexedList so I can have an array of just the even index based elements and an array of odd based index elements.
Ramda's list-based functions by default do not deal with indices. This, in part, is because many of them are more generic and also work with other data structures where indices don't make sense. But there is a standard mechanism for altering functions so that they do pass the indices of your lists along: addIndex.
So my first thought on this is to first of all, take your isEven and extend it to
var indexEven = (val, idx) => isEven(idx);
Then you can use addIndex with filter and reject like this:
R.addIndex(R.filter)(indexEven, ['a', 'b', 'c', 'd', 'e']);
//=> ['a', 'c', 'e']
R.addIndex(R.reject)(indexEven, ['a', 'b', 'c', 'd', 'e']);
//=> ['b', 'd']
Or if you want them both at once, you can use it with partition like this:
R.addIndex(R.partition)(indexEven, ['a', 'b', 'c', 'd', 'e']);
//=> [["a", "c", "e"], ["b", "d"]]
You can see this in action, if you like, on the Ramda REPL.
If the list length is even, I would go with
R.pluck(0, R.splitEvery(2, ['a','b','c']))
The disadvantage of this is that it will give undefined as a last element, when list length is odd and we want to select with offset 1 ( R.pluck(1) ). The advantage is that you can easily select every nth with any offset while offset < n.
If you can't live with this undefined than there is another solution that I find more satisfying than accepted answer, as it doesn't require defining a custom function. It won't partition it nicely though, as the accepted answer does.
For even:
R.chain(R.head, R.splitEvery(2, ['a','b','c','d']))
For odd:
R.chain(R.last, R.splitEvery(2, ['a','b','c','d']))
As of Ramda 0.25.0, the accepted solution will not work. Use this:
const splitEvenOdd = R.compose(R.values, R.addIndex(R.groupBy)((val,idx) => idx % 2))
splitEvenOdd(['a','b','c','d','e'])
// => [ [ 'a', 'c', 'e' ], [ 'b', 'd' ] ]

Replace in array using lodash

Is there an easy way to replace all appearances of an primitive in an array with another one. So that ['a', 'b', 'a', 'c'] would become ['x', 'b', 'x', 'c'] when replacing a with x. I'm aware that this can be done with a map function, but I wonder if have overlooked a simpler way.
In the specific case of strings your example has, you can do it natively with:
myArr.join(",").replace(/a/g,"x").split(",");
Where "," is some string that doesn't appear in the array.
That said, I don't see the issue with a _.map - it sounds like the better approach since this is in fact what you're doing. You're mapping the array to itself with the value replaced.
_.map(myArr,function(el){
return (el==='a') ? 'x' : el;
})
I don't know about "simpler", but you can make it reusable
function swap(ref, replacement, input) {
return (ref === input) ? replacement : input;
}
var a = ['a', 'b', 'a', 'c'];
_.map(a, _.partial(swap, 'a', 'x'));
If the array contains mutable objects, It's straightforward with lodash's find function.
var arr = [{'a':'a'}, {'b':'b'},{'a':'a'},{'c':'c'}];
while(_.find(arr, {'a':'a'})){
(_.find(arr, {'a':'a'})).a = 'x';
}
console.log(arr); // [{'a':'x'}, {'b':'b'},{'a':'x'},{'c':'c'}]
Another simple solution. Works well with arrays of strings, replaces all the occurrences, reads well.
var arr1 = ['a', 'b', 'a', 'c'];
var arr2 = _.map(arr1, _.partial(_.replace, _, 'a', 'd'));
console.log(arr2); // ["d", "b", "d", "c"]

Categories

Resources