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 an array
var hashtags = [ '#hr', '#acc', '#sales', '#hr' ];
I understand that to look for a specified matching value I'd have to use this
if (hashtags.indexOf("#hr") > -1)
// output value
But how do I output ALL the matching values that match the condition?
You can use Array#filter and equality comparison to get all the occurrences of your word in the given array.
var hashtags = [ '#hr', '#acc', '#sales', '#hr' ];
var result = hashtags.filter( word => word === '#hr');
console.log(result);
You can use Array#filter and check inside the condition. Also instead of indefOf you can use Array#includes function.
const hashtags = [ '#hr', '#acc', '#sales', '#hr' ];
const filteredHashtags = hashtags.filter(item => item.includes('#hr'));
console.log(filteredHashtags);
string [] arr = {"One","Two","Three"};
var target = "One";
var results = Array.FindAll(arr, s => s.Equals(target));
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)
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"]
I have:
var array = new Array();
array.push("A");
array.push("B");
array.push("C");
I want to be able to do something like:
array.remove("B");
but there is no remove function. How do I accomplish this?
I'm actually updating this thread with a more recent 1-line solution:
let arr = ['A', 'B', 'C'];
arr = arr.filter(e => e !== 'B'); // will return ['A', 'C']
The idea is basically to filter the array by selecting all elements different to the element you want to remove.
Note: will remove all occurrences.
EDIT:
If you want to remove only the first occurence:
t = ['A', 'B', 'C', 'B'];
t.splice(t.indexOf('B'), 1); // will return ['B'] and t is now equal to ['A', 'C', 'B']
Loop through the list in reverse order, and use the .splice method.
var array = ['A', 'B', 'C']; // Test
var search_term = 'B';
for (var i=array.length-1; i>=0; i--) {
if (array[i] === search_term) {
array.splice(i, 1);
// break; //<-- Uncomment if only the first term has to be removed
}
}
The reverse order is important when all occurrences of the search term has to be removed. Otherwise, the counter will increase, and you will skip elements.
When only the first occurrence has to be removed, the following will also work:
var index = array.indexOf(search_term); // <-- Not supported in <IE9
if (index !== -1) {
array.splice(index, 1);
}
List of One Liners
Let's solve this problem for this array:
var array = ['A', 'B', 'C'];
1. Remove only the first:
Use If you are sure that the item exist
array.splice(array.indexOf('B'), 1);
2. Remove only the last:
Use If you are sure that the item exist
array.splice(array.lastIndexOf('B'), 1);
3. Remove all occurrences:
array = array.filter(v => v !== 'B');
DEMO
You need to find the location of what you're looking for with .indexOf() then remove it with .splice()
function remove(arr, what) {
var found = arr.indexOf(what);
while (found !== -1) {
arr.splice(found, 1);
found = arr.indexOf(what);
}
}
var array = new Array();
array.push("A");
array.push("B");
array.push("C");
remove(array, 'B');
alert(array);
This will take care of all occurrences.
Simply
array.splice(array.indexOf(item), 1);
Simple solution (ES6)
If you don't have duplicate element
Array.prototype.remove = function(elem) {
var indexElement = this.findIndex(el => el === elem);
if (indexElement != -1)
this.splice(indexElement, 1);
return this;
};
Online demo (fiddle)
const changedArray = array.filter( function(value) {
return value !== 'B'
});
or you can use :
const changedArray = array.filter( (value) => value === 'B');
The changedArray will contain the without value 'B'
In case of wanting to remove array of strings from array of strings:
const names = ['1','2','3','4']
const excludeNames = ['2','3']
const filteredNames = names.filter((name) => !excludeNames.includes(name));
// ['1','4']
You have to write you own remove. You can loop over the array, grab the index of the item you want to remove, and use splice to remove it.
Alternatively, you can create a new array, loop over the current array, and if the current object doesn't match what you want to remove, put it in a new array.
use:
array.splice(2, 1);
This removes one item from the array, starting at index 2 (3rd item)
use array.splice
/*array.splice(index , howMany[, element1[, ...[, elementN]]])
array.splice(index) // SpiderMonkey/Firefox extension*/
array.splice(1,1)
Source:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
This only valid on str list, look up this
myStrList.filter(item=> !["deletedValue","deletedValue2"].includes(item))
Here is the simplest answer.
First find index using indexofand then
if index exist use splice
const array = ['apple', 'banana', 'orange', 'pear'];
const index = array.indexOf('orange'); // Find the index of the element to remove
if (index !== -1) { // Make sure the element exists in the array
array.splice(index, 1); // Remove the element at the found index
}
console.log(array); // ["apple", "banana", "pear"]