How to remove an element in array if it has particular characters? - javascript

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)

Related

How to find indexes of multiple elements in array with second array elements and then use result to match index of third array (Javascript)

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);

Toggle text between arrays ( jQuery )

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);

creating new values by index in JS looping/arrays

I have an array of values:
let myArray = [ 'Ifmanwas',
'meanttos',
'tayonthe',
'groundgo',
'dwouldha',
'vegivenu',
'sroots' ]
I want to print out a new value for each item in the array so that the first item is a collection of all the characters at the zero index, the second is a collection of all the characters at the 1 index position, ect...
So for instance, the output of the first array would be "Imtgdvs" (all the letters at ("0"), the second would be "fearwer" (all the letters at index "1") ect...
I am very lost on how to do this and have tried multiple different ways, any help is appreciated.
For this simple attempt I have created an array of all the letters for the first instance:
function convertToCode(box) {
let arr = [];
for (i = 0; i < box.length; i++) {
let counter = i;
let index = box[counter];
let letter = index.charAt(0);
arr.push(letter);
}
console.log(arr);
}
convertToCode(myArray)
Thanks
The main issue in your example is this: index.charAt(0);. This will always get the first character, whereas you need a nested loop.
You could use Array.map() in combination with Array.reduce(), like so:
let myArray = ['Ifmanwas','meanttos','tayonthe','groundgo','dwouldha','vegivenu','sroots'];
const result = Array.from(myArray[0]) //Create an array as long as our first string
.map((l,idx) => //Update each item in that array...
myArray.reduce((out,str) => str[idx] ? out+str[idx] : out, "") //to be a combination of all letters at index [idx] from original array
);
console.log(result);
Note that this uses the first string in the array to decide how many strings to make, as opposed to the longest string.

Remove all elements from array of strings that do not contain "IN"

I need to remove all elements in an array that do not contain "IN" in uppercase exactly like that.
How I thought of doing this was to traverse the array with a for loop and write all values that contain IN to another array.
Is there a way I can do it without writing to a new array and just removing those items that don't match from the current array?
Here is the code for how I was planning on doing it:
arrTwo = [];
for(var i = 0; i<arr.length; i++){
if(arr[i].indexOf('IN') > -1) arrTwo.push[arr[i]];
}
You can use ES5 filter method:
arr = arr.filter(function(s){
return ~s.indexOf("IN");
});
And using ES6 arrow functions, it can be simplified to:
arr = arr.filter(s=>~s.indexOf("IN"));
Here's a really good thread that has a couple of ways to accomplish this. If you do not delete the element of the array in the correct manner, you that element will be undefined rather than actually deleted. The .spilce() method is what you want to look into.
Deleting array elements in JavaScript - delete vs splice
I would do it using the splice() method:
var testArray = [ 'this one contains IN', 'this one does not' ];
function filterArray ( arr ) {
var i = arr.length;
//-- Loop through the array in reverse order since we are modifying the array.
while (i--) {
if (arr[i].indexOf('IN') < 0) {
//-- splice will remove the non-matching element
arr.splice(i, 1);
}
}
}
filterArray( testArray );
document.body.innerText = JSON.stringify(testArray);
JSFiddle: http://jsfiddle.net/5DW8L/1/

Javascript check every char in a string and return array element on corresponding position

Got a string that is a series of 0 or 1 bit and an array of values, if in the string are characters that are set to 1, I need to return the corresponding value from the array.
example: mystring = "0101"; myarray =["A","B","C","D"]; then result = "B,D"
how can I get this result?
for(var i=0;i<mystring.length;i++){
if(mystring[i] != 0)
{
result = myarray[i];
}
}
Your code seems to work just fine, so you can just add another array and push the values on to that:
var result = [];
for (var i = 0 ...
result.push(myarray[i]);
http://jsfiddle.net/ExplosionPIlls/syA2c/
A more clever way to do this would be to apply a filter to myarray that checks the corresponding mystring index.
myarray.filter(function (_, idx) {
return +mystring[idx];
})
http://jsfiddle.net/ExplosionPIlls/syA2c/1/
Iterate through the characters in the binary string, if you encounter a 1, add the value at the corresponding index in the array to a temporary array. Join the temporary array by commas to get the output string.
I am not really sure if this is what you are looking for, but this returns the array of matches.
var result = [];
for(var i=0;i<mystring.length;i++){
if(parseInt(mystring[i]) !== 0 ) {
result.push(myarray[i]);
}
}
return result;
result = new Array();
for(var i=0;i

Categories