I have a function displaySelectedRole() and I have variables $scope.Role and $scope.rolenames .I need to remove all values available in $scope.role from $scope.rolename.
$scope.role= ["A","B","C"];
$scope.rolename =["A","B","C","D","E"]
I need to splice the values and get $scope.rolename = ["D","E"]
$scope.displaySelectedRole = function(role, index) {
debugger;
$scope.role.splice(RoleNames[index]);
console.log($scope.role);
I tried to use splice based on index , but problem is it given empty array values in console.
You can use filter
var $scope = {}; // Ignore this line
$scope.role= ["A","B","C"];
$scope.rolename = ["A","B","C","D","E"];
$scope.rolename = $scope.rolename.filter(function(role){
return $scope.role.indexOf(role) === -1;
})
console.log($scope.rolename);
If you want to remove them directly you could iterate through the $scope.role and use splice
var $scope = {}; // Ignore this line
$scope.role= ["A","B","C"];
$scope.rolename = ["A","B","C","D","E"];
$scope.role.forEach(function(role){
var index = $scope.rolename.indexOf(role);
if(index !== -1) $scope.rolename.splice(index, 1);
})
console.log($scope.rolename);
Note: Array.filter will return a new array, unlike array.splice which will modify original array.
Reference
Array.filter
You can you Underscore.js's difference(), it purposes a method to substract arrays:
$scope.role = ["A","B","C"];
$scope.rolename = ["A","B","C","D","E"];
$scope.diff = _.difference($scope.rolename, $scope.role); // ["D","E"]
Related
Hope title is not too confusing but further explanation below.
var listName = ["Alexandros","Halvar","Herman","Luciano","Natana","Nihal","Priscilla","Tanja","Trish","Trish"]
var listID = ["10","6","4","8","1","7","2","3","5","9"]
var newList = ["Luciano","","Priscilla","Herman","Trish","Trish","Natana","Tanja","Nihal","Alexandros"]
I'm trying to find the index of each newList element in listName and then use the result to match the index in listID.
Afterwards create new array with the results like such:
var result = ["8","","2","4","5,9","5,9","1","3","7","10"]
With some help from this thread, this is as far i have gotten:
for (var i = 0; i < listName.length; i++) {
function getAllIndexes(arr, val) {
var indexes = [], i = -1;
while ((i = arr.indexOf(val, i+1)) != -1){
indexes.push(i);
}
return indexes;
}
var indexes = getAllIndexes(listName, newList[i]);
var result = []
result.push(String(listID[indexes]));
alert(result);
}
Result is good but returns undefined with elements that has two or more values (5,9).
Any help appreciated.
indexes is an array of indexes, you can't use it to index listID directly. Use map() to get the contents of all the indexes.
result.push((indexes.map(i => listID[i]).join(","))
It works when there are no duplicates because when an array is converted to a string, it becomes the array elements separated by comma. So when indexes only has one element, it's converted to that element, which is a valid array index.
By creating a map of name -> indexes from the listName array, you can make this problem much easier and efficient to solve.
After you have a map of which names correspond to which index, you can then iterate through the newList and use the indexes in the map to then grab the value out of the corresponding index in the listID array. Then simply join them with a , to get your desired output format.
var listName = ["Alexandros","Halvar","Herman","Luciano","Natana","Nihal","Priscilla","Tanja","Trish","Trish"]
var listID = ["10","6","4","8","1","7","2","3","5","9"]
var newList = ["Luciano","","Priscilla","Herman","Trish","Trish","Natana","Tanja","Nihal","Alexandros"]
let listIndexes = listName.reduce((res, curr, index) => {
if (!res[curr]){
res[curr] = [];
}
res[curr].push(index);
return res;
}, {});
let ids = newList.map((name) => {
let results = (listIndexes[name] || []).map(index => listID[index]);
return results.join(",");
});
console.log(ids);
I have two arrays and the idea is to find text in first array and replace itwith the value of second array ( Same index ).
Example
Text to search & replace: Visina
var array1 = ['Visina','Tezina'];
var array2 = ['Height','Weight'];
So the script should search for "Visina" in first array, find the index and replace with the value from second array with same index.
Also, it needs to toggle.
Well, you simply should use Array.indexOf() method:
var array1 = ['Visina', 'Tezina'];
var array2 = ['Height', 'Weight'];
function swap(str) {
const index = array1.indexOf(str);
if (index !== -1) {
array1[index] = array2[index];
array2[index] = str;
}
}
swap('Visina');
console.log(array1);
console.log(array2);
I am trying to push items from one Array to another depending on the order that is supplied. Essentially i have a 2d array with a name and a price :
var myArray = [['Apples',22],['Orange',55],['Berry',23]];
Another array with the order it should be in :
var myOrder = [0,2,1];
My resulting array would look like this :
var finalArray = [['Apples',22],['Berry',23],['Orange',55]]
My initial thought process was to loop through myArray and loop through myOrder , store the object temporary at a specified index in myOrder then push to final array. I think i am over thinking it a bit, i made several attempts but with no luck whatsoever. Any help would be greatly appreciated!
This is a simple map() that doesn't require anything else
var myArray = [['Apples',22],['Orange',55],['Berry',23]];
var myOrder = [0,2,1];
let final = myOrder.map(i => myArray[i])
console.log(final)
The optimal way appears to me to be:
Initialize empty finalArray
Loop over your myOrder array
2.1. Push myArray[index] to finalArray
Like so:
let finalArray = [];
for(let index of myOrder) {
finalArray.push(myArray[index]);
}
Review the for...of syntax if you're not familiar with it.
You can use splice to insert so long as the same number of elements are present in both the arrays.
You iterate over the myOrder array and then use splice, to which the index of the new array is the current value of the iteration and then use array present in the index position of myArray
var myArray = [['Apples',22],['Orange',55],['Berry',23]];
var myOrder = [0,2,1];
var finalArray = [];
myOrder.forEach(function(val, index) {
finalArray.splice(val, 0, myArray[index]);
});
console.log(finalArray);
Easy enough using .reduce:
var myArray = [['Apples',22],['Orange',55],['Berry',23]];
var myOrder = [0,2,1];
function reorder(array, order) {
return order.reduce((newArray, orderIndex) => {
newArray.push(array[orderIndex]);
return newArray;
}, []);
}
console.log(reorder(myArray, myOrder))
function reorder(arr, order) {
return order.map(function(i) {
return arr[i];
});
}
var myArray = [['Apples',22],['Orange',55],['Berry',23]];
var myOrder = [0,2,1];
reorder(myArray, myOrder); // => [["Apples",22],["Berry",23],["Orange",55]]
One of way solving this will be
var myArray = [['Apples',22],['Orange',55],['Berry',23]];
var myOrder = [0,2,1];
var finalArray;
for (x in myOrder) {
finalArray[x] = myArray[myOrder[x]];
}
This is a beginning level solution. Also you use libraries available for java script such as underscore.js(http://underscorejs.org/) for such operations on Array and Object.
Also you can use ECMA 6, for doing this which will reduce your line of coding.
Example-
var myArray = [['Apples',22],['Orange',55],['Berry',23]];
var myOrder = [0,2,1];
let finalArray = myOrder.map(i => myArray[i])
This is the new way of coding in javascript.
In my point of view, it will be easy if you learn latest version of Java script(ECMAscript 6)
I want to remove the elements from the array if it contains particular values.
var array = [hello#yahoo.com, www.hello.com, hello#gmail.com];
I want to remove the al elements which has # signs. when I alert the array I need only www.hello.com.
array.forEach(function(element, key) {
if (element.indexOf('#') !== -1) {
array.splice(key, 1);
}
});
Avoid deleting/changing index of elements of array inside a loop. This is because the array is being re-indexed when you do a .splice(), which means you'll skip over an index when one is removed,
Instead you can filter out the element and get a new array which match your criteria
var array = [
'hello#yahoo.com',
'www.hello.com',
'hello#gmail.com'];
var newArray = array.filter(function(item){
return item.indexOf('#') ==-1
})
console.log(newArray)
DEMO
One way to do this is to use a Regular Expression, along with another array, like so:
var array = ['hello#yahoo.com', 'www.hello.com', 'hello#gmail.com'];
var array2 = [];
for (var i = 0; i < array.length; i++) {
if (!(/#/.test(array[i]))) {
array2.push(array[i]);
};
};
alert(array2);
You can also loop the input array and push element that match into the output array
var array = [
'hello#yahoo.com',
'www.hello.com',
'hello#gmail.com'];
var newArray = [];
array.forEach(x => {
if(x.indexOf('#') === -1)
newArray.push(x);
});
console.log(newArray)
Here is my function:
function RemoveOutputKeys(array){
var temp = array;
for(var object in temp){
delete temp[object]['statusCode']
delete temp[object]['statusResponse']
}
console.log(array)
if(temp == array)
console.log("how is this possible?!?!!?!?!")
return temp
}
and here is the input I am providing,
array = [{'statusCode':400},{'statusCode':200}]
It makes sense for temp to get updated but I don't want the array to get updated. How can i fix this issue?
Thanks
Use Array.prototype.filter() instead of for in
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
function RemoveOutputKeys(array) {
return array.filter(function(myArray) {
if (!myArray['statusCode'] && !myArray['statusResponse']) {
return myArray;
}
});
}
var originalArray = [{'statusCode':400}, {'statusCode':200}, {'test': 'test'}];
var tempArray = RemoveOutputKeys(originalArray);
console.log(originalArray, tempArray);
https://jsfiddle.net/3kbypvcs/2/
If you want create new array instead of alias/reference use:
var newArray = oldArray.slice();