Using Underscore.js's invoke with lastIndexOf - javascript

// Why doesn't this:
_.invoke(['D','C'], 'lastIndexOf', ['A','B','C'])
// Return this:
[-1,2]?
I've got a string. (Input)
'ABC'
Split into an array. (InputBuffer)
['A','B','C']
I've also got an array with arbitrary characters. (TriggerChars)
['D','E']
I want to check the last item in the InputBuffer to see if matched any of the TriggerChars.
I want to get the last occurrence of both TriggerChars in the InputBuffer.
_.invoke(['D','E'], 'lastIndexOf', ['A','B','C']);
// Returns [-1,-1] since C isn't D or E.
_.invoke(['D','C'], 'lastIndexOf', ['A','B','C']);
// Why doesn't this return [-1,2]
_.lastIndexOf(['A','B','C'],'D') == -1
_.lastIndexOf(['A','B','C'],'C') == 2
What am I not getting with Invoke?
http://underscorejs.org/#invoke

var InputBuffer = ["A","B","C"];
var TriggerChars = ["D","E"];
_.indexOf( TriggerChars, InputBuffer[InputBuffer.length-1] ) > -1;
Evaluates to true if this: I want to check the last item in the InputBuffer to see if matched any of the TriggerChars.

What you need is:
_.map(['D', 'C'], function (x) { return _.lastIndexOf(['A', 'B', 'C'], x)})

var inputBuffer = ["A","B","C"];
var triggerChars = ["D","E"];
triggerChars.indexOf(inputBuffer[inputBuffer.length-1]) > -1
or just skip underscore, the exact same solution above except the dependency,
ok I updated it alittle
var inputBuffer = ["A","B","C"];
var triggerChars = ["D","C"];
var index = [];
for(var i = 0; i < triggerChars.length; i++){
index.push(inputBuffer.lastIndexOf(triggerChars[i]));
}
console.log(index);
-> [-1,2]

Related

Get the value that is not matched with matching element from array with two elements

I have array of two elements
var a = ['a','b'];
I have remover variable as var remover = 'a'
i want the result variable as var result = 'b'
i tried it as
var current_id = 'windows123456';
var allIds = People.Ids(); // this will have ['windows123456','windows123']
var index = allIds.indexOf(current_id);
if (index >= 0) {
allIds.splice( index, 1 );
}
console.log(allIds[0]); //windows123
Any Easy way to do this??
If you only need to do this for two-element arrays, this will work:
var result = a.find(item => item != remover);
If you need to work with longer arrays, this returns ['b']:
var result = a.filter(item => item != remover);
You may destructure the array:
var [remover,result]=a;

Printing array values by a repeating pattern

var arr = [a, b, c];
In above array,
index 0 contains "a",
index 1 contains "b",
index 2 contains "c".
console.log(arr[0]) // will print > "a"
console.log(arr[1]) // will print > "b"
console.log(arr[2]) // will print > "b"
Is there a way so that if I want to console.log(arr[3]) then it should print "a" again, console.log(arr[4]) would be "b" and so on. If we want an index of let's say 42 like this console.log(arr[42]) then it should print any of those three string values by following the same pattern.
simply use with % like this arr[value % arr.length].
var arr = ['a', 'b', 'c'];
function finding(val){
return arr[val % arr.length];
}
console.log(finding(0))
console.log(finding(1))
console.log(finding(2))
console.log(finding(3))
console.log(finding(4))
console.log(finding(5))
console.log(finding(6))
console.log(finding(42))
We can define our custom function which give the appropriate index
function getIndex(num){
return num%3;/* modulo operator*/
}
var arr=["a","b","c"];
console.log(arr[getIndex(0)]);
console.log(arr[getIndex(1)]);
console.log(arr[getIndex(2)]);
console.log(arr[getIndex(3)]);
console.log(arr[getIndex(4)]);
console.log(arr[getIndex(5)]);
console.log(arr[getIndex(41)]);
We cannot have exactly what you are looking for. But what we can have what you are looking for by this
var arr = ["a","b","c"];
var printToThisIteration = function(n){
var length = arr.length;
for(i=0;i<n;++i)
{
console.log(arr[i%length])
}
}
Using % you can have it repeat as many times as you like.
var arr = ['a','b','c'];
let repetitions = 5;
for(var i = 0; i < repetitions; i++){
console.log(arr[i%3]);
}

Integer arrays comparison

I have a question of JS arrays.
Example:
var fullArr = [1,2,3,4];
var partArr = [2,3];
var newArr = [];
We have a main array fullArr and a partial array partarr. I want to create a function/filter, which is looking for existing items in fullArr and not in partArr.
In this example above newArr must be equal to [1,4].
I've tried doing something like this, but it's not working properly.
for (var k in fullArray) { // [1,2,3,4]
for (var j in selectedArray) { // [1,4]
if (fullArray[k] == selectedArray[j]) {
newArray.splice(selectedArray[j] - 1, 1); // must be [2,3]
break;
}
}
}
What is a good way of making this? Thanks.
Here's one
var newArr = fullArr.filter(function(f) { // The filter() method creates a new array with all elements that pass the test implemented by the provided function.
return partArr.indexOf(f) == -1; // The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
})
to impress the girls, you can also
var newArr = fullArr.filter(function(f) {
return !~partArr.indexOf(f);
})
Here is the code for your requirement.
var fullArr = [1,2,3,4];
var partArr = [2,3];
var newArr = [];
for(var i=0;i<fullArr.length;i++){
if(partArr.indexOf(fullArr[i]) == -1)
newArr.push(fullArr[i]);
};
Here is the working Link
Hope it works :)
In fact, you want a common part between arrays. Obviously you can choose splice or indexOf to have O(n * m) or even O(m * n^2) performance. It's obviously suboptimal for any array larger than few elements
Or you can use objects as hash maps to find differences in (in worst case) O(n + m log m):
var fullArr = [1,2,3,4];
var partArr = [2,3];
var temporaryObject = Object.create(null);
partArr.forEach(el=>temporaryObject[el] = true); // temporaryObject after this operation is {"2": true, "3": true}
var newArr = fullArr.filter(el=>temporaryObject[el]);
In this example I have used ES6 feature called "arrow functions". It translates to following ES5 code:
var partArr = [2, 3];
var temporaryObject = Object.create(null);
partArr.forEach(function (el) {
temporaryObject[el] = true;
}); // temporaryObject after this operation is {"2": true, "3": true}
var newArr = fullArr.filter(function (el) {
return temporaryObject[el];
});
You can use the filter() function that works on arrays:
var newArr = fullArr.filter(function(val, i, arr) {
return partArr.indexOf(val) === -1;
});
This will return a new array containing the values of every iteration that returns true.
Should you ever need to do this on an object in the future a great way is to first convert the object keys to an array and then run the filter:
Object.keys(myObj).function(val, i, arr) {
return partArr.indexOf(val) === -1;
});
Here are few other approaches:
var fullArr = [1,2,3,4];
var partArr = [2,3];
var newArr = [];
1.
fullArr.map(function(element){
if(partArr.indexOf(element) === -1) newArr.push(element);
})
console.log(newArr);
2.
for(i in fullArr){
if(partArr.indexOf(fullArr[i]) === -1) newArr.push(fullArr[i]);
}
console.log(newArr);
3.
fullArr.forEach(function(element){
if(partArr.indexOf(element) === -1) newArr.push(element);
})
console.log(newArr);

Deleting from an array based on a string value

I have defined an array like so :
var myArray = {myNewArray: ['string1' , 'string2' , 'string3']};
I want to iterate over the array and delete an element that matches a particular string value. Is there a clean way in jQuery/javascript to achieve this ?
Or do I need to iterate over each element, check its value and if its value matches the string im comparing, get its id and then use that id to delete from the array ?
Here's a JSFiddle showing your solution
var strings = ['a', 'b', 'c', 'd'];
document.write('initial data: ' + strings);
var index = 0;
var badData = 'c';
for(index = 0; index < strings.length; index++)
{
if(strings[index] == badData)
{
strings.splice(index, 1);
}
}
document.write('<br>final data: '+ strings);​
JavaScript arrays have an indexOf method that can be used to find an element, then splice can be used to remove it. For example:
var myNewArray = ['A', 'B', 'C'];
var toBeRemoved = 'B';
var indexOfItemToRemove = myNewArray.indexOf(toBeRemoved);
if (indexOfItemToRemove >= 0) {
myNewArray.splice(indexOfItemToRemove, 1);
}
After that code executes, myNewArray is ['A', 'C'].
You can use Array.filter.
filteredArray = myArray.myNewArray.filter(function(el){
return el === "string";
});
You can check compatibility at Kangax's compat tables.
You could filter the array using $.grep
var myArray = {myNewArray: ['string1' , 'string2' , 'string3']};
myArray = { myNewArray: $.grep(myArray.myNewArray,function(val){
return val !== "string1";
})};
//console.log(myArray);
my newARR = oldArr.splice( $.inArray( removeItem , oldArr ) , 'deleteThisString');

How can i delete something out of an array?

My problem is that i have to delete something out of an array. I found out how to delete something out of a listbox. But the problem is that the listbox is filled by an array. So if I don't delete the value (I deleted out of the listbox) out of the array. The value keeps coming back when you add a new item. BTW: I am new to php and javascript.
My code is:
function removeItem(veldnaam){
var geselecteerd = document.getElementById("lst"+veldnaam).selectedIndex;
var nieuweArray;
alert(geselecteerd);
alert(document.getElementById(veldnaam+'hidden').value);
For (var i = 0, i<= arr.lenght, i++) {
If (i= geselecteerd){
nieuweArray = arr.splice(i,1);
document.getElementById(veldnaam+'hidden').value = arr;
}}
document.getElementById("lst"+veldnaam).remove(geselecteerd);
}
Use the delete operator. I'm assuming you are using objects as associative arrays.
var arr = {
"hello": "world",
"foo": "bar"
}
delete arr["foo"]; // Removes item with key "foo"
You can delete elements in an array using the delete command. But it will just set the value to undefined.
var arr = ['h', 'e', 'l', 'l', 'o'];
delete arr[2];
arr => ['h', 'e', undefined, 'l', 'o'];
So it will not remove the item, and make a shorter array, the array will still have 5 elements (0 to 4), but the value has been deleted.
In the case of "associative" arrays, or objects: The property will get erased and it will no longer exist.
var obj = { 'first':'h', 'second':'e', 'third':'l'};
delete obj['first'];
obj => { 'second':'e', 'third':'l'};
Add the following code somewhere
// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
and call it like this:
// Remove the second item from the array
array.remove(1);
// Remove the second-to-last item from the array
array.remove(-2);
// Remove the second and third items from the array
array.remove(1,2);
// Remove the last and second-to-last items from the array
array.remove(-2,-1);
Article containing the code above and explanation: http://ejohn.org/blog/javascript-array-remove/
var geselecteerd = document.getElementById("lst"+veldnaam).selectedIndex;
var nieuweArray;
var teller = 0;
var oudeArray=document.getElementById(veldnaam+'hidden').value;
var tmpArr="";
nieuweArray=oudeArray.split(":");
for (i = 0; i<nieuweArray.length; i++){
if (!(i==geselecteerd)){
tmpArr = tmpArr+nieuweArray[i]+":";}
teller++;
}
tmpArr = tmpArr + ":";
tmpArr = tmpArr.replace("::","");
document.getElementById(veldnaam+'hidden').value = tmpArr;
document.getElementById("lst"+veldnaam).remove(geselecteerd);
}
This is my solution and it worked. Thanks for your help.

Categories