How utilize array.splice() method in if statement [duplicate] - javascript

This question already has answers here:
Looping through array and removing items, without breaking for loop
(17 answers)
Remove Strings, Keep Numbers In Array With JavaScript
(5 answers)
How to remove all the numbers from an array?
(4 answers)
Closed 3 months ago.
I am trying to iterate over an array of strings with a "mistake" element that needs to be spliced. How can I utilize the array.splice() method to remove that item, in this case a typeof "number" within an array of strings? The below code returns the original array with the 'number' still present.
var inputFunction = function filterOutNumbers(array) {
// iterate over input array
for (var i = 0; i < array.length; i++) {
// if type of current value is not equal to string, delete current value
if (typeof array[i] !== 'string') {
array.splice(array[i]);
}
}
return array;
}
var inputArray = ['only', 'words', 'go', 'in', 78, 'here']
var output = inputFunction(inputArray);
console.log(output); // should log ['only', 'words', 'go', 'in', 'here']

The easier way to go about it would be to use filter() to create a filtered copy of the array:
const array = ['only', 'words', 'go', 'in', 78, 'here'];
const result = array.filter(v => typeof v === 'string');
console.log(result);
If you insist on modifying the array in place with splice():
const array = ['only', 'words', 'go', 'in', 78, 'here'];
for (let i = array.length - 1; i >= 0; i--) {
if (typeof array[i] !== 'string') array.splice(i, 1);
}
console.log(array);
It's important here to iterate in reverse. If you iterate forward, the index values will no longer match once you splice the array, resulting in elements being skipped.
Also look at the documentation for splice(). The usage in your original code is incorrect.

Related

position array elements in ascending order (numbers are found as substrings inside the array elements) [duplicate]

This question already has answers here:
Natural sort of alphanumerical strings in JavaScript
(6 answers)
Javascript sort on on part of string
(4 answers)
Closed 7 months ago.
I have an array, I want to position every array element in ascending order but the numbers are found as substrings of the array elements. I sketched the code below to give you an idea of what I am trying to achieve(it works but its ugly). What is the best way to position every element inside an array in ascending order when the numbers are found as substrings inside the array elements. Thanks in advance.
Take a look at my code to better understand my question!
//this works but is uglyyyyy
const myArray = ['test4.js', 'test3.js', 'test1.js', 'test2.js']
let tempArr = []
for (var i = 0; i < myArray.length; i++) {
tempArr.push(myArray[i].replace('test', '').replace('.js', ''))
}
const sortedTempArr = tempArr.sort()
let sortedArray = []
for (var i = 0; i < sortedTempArr.length; i++) {
for (var j = 0; j < myArray.length; j++) {
if (myArray[j].includes(sortedTempArr[i])) {
sortedArray.push(myArray[j])
}
}
}
console.log(sortedArray)
Yes that was ugly ;)
Sort takes a function
For descending, switch a and b
I am assuming only ONE number in the string. The regex will produce a wrong result if you have test2version1.js for example
//this works and is pretty
const myArray = ['test4.js', 'test3.js', 'test11.js', 'test1.js', 'test.js', 'test2.js'];
const re = /\D+/g; // anything not a number
const sortedArray = myArray
.slice(0) // shallow copy
.sort((a, b) => a.replace(re, "") - b.replace(re, ""));
console.log(sortedArray);
.sort() the .match(/\d+/)[0] number of each string (coerced into a number). The bracket notation ([0]) ensures that only the first match is used and everything else is ignored.
const array = ['test4.js','test11.js', 'test3.js', 'test1.js', 'test2.js'];
let result = array.sort((a, b) => +a.match(/\d+/)[0] - b.match(/\d+/)[0]);
console.log(result);

Mutation of an array's copy also mutates the original array! Why? [duplicate]

This question already has answers here:
Why can't I make a copy of this 2d array in JS? How can I make a copy?
(2 answers)
Closed 2 years ago.
I have the following function to rotate a matrix 90deg and this is the code
function rotateMatrix(array) {
let counter = 0;
let resultArr = array.slice();
let i = 0,
k = 0,
p = 0;
j = array.length - 1;
console.log(array === resultArr); //false
while (counter <= Math.pow(array.length, 2)) {
if (i < array.length) {
resultArr[k][p] = array[i][j];
i++;
p++;
} else {
j--;
k++;
i = 0;
p = 0;
}
}
return resultArr;
}
Even though I created a copy of the array whenever I try to mutate the resultArr to insert the values for the rotated matrix, both of the arrays (resultArr & array) gets mutated, when I compare (resultArr === array) it gives me false.
As you can see here:
Capture of both arrays in the debbuger
Does anyone have an idea why is this happening?
If you want to create a brand new two-dimensional array, you can use a code like following:
const array=[[1,2],[3,4]],
array2=array.slice().map(el=>el.slice());
console.log(array2==array); // false
console.log(array2[0]==array[0]); // false
or
const array=[[1,2],[3,4]],
array2=Array.from(array).map(el=>Array.from(el));
The array variable is not actually directing to the values stored in it like other numeric or character variables.
It stores the base address of the memory location where the array values are stored. So if you make a copy using
var copyArray = actualArray.slice();
a new copy of the actual array is created and stored in an another location of memory. At this time the new array variable points to the base address of copied array in memory. when you perform comparison over arrays like
array1 === array2
the system is not matching the values stored in it, but the base memory address of each array. Two memory location will not have same address at all. so it will give a false.
examples:
1
var ar1 = [];
var ar2 = [];
console.log(ar1 === ar2); // false
2
var ar1 = [];
var ar2 = ar1.slice();
console.log(ar1 === ar2); // false
3
var ar1 = [];
var ar2 = ar1;
console.log(ar1 === ar2); // true
I think you understood why you got the false from the comparison.

Compare elements in array for similarity js [duplicate]

This question already has answers here:
Check if all values of array are equal
(33 answers)
Closed 6 years ago.
I have an array for example
var a = [1,4,6,1,1,1,1];
and I need to compare each element in array for similarity. If all of them are similar I need return true, if one or more of them are different it should return false
Will be glad to get the answer.
Here's one method to achieve it, by using Set.
var a = [1,1,1,1];
var b = [1,2,3,4,5,1,2,3];
function check(arr) {
console.log([...new Set(arr)].length == 1 ? true : false);
}
check(a);
check(b);
if they all need to be the same then you could just check to see if everything in the array is equal to the first element by using filter and length. The length of the array filtered by any element in the list should equal the original length.
const a = [1, 4, 1, 1, 1, 1, 1];
function similarity(arr) {
let firstItem = arr[0];
return arr.filter(elements => elements == firstItem).length != arr.length ? false : true;
}
console.log(similarity(a));
You can make use of the every Method.
From MDN
The every() method tests whether all elements in the array pass the
test implemented by the provided function.
var notsimilar= [1,4,6,1,1,1,1];
var similar= [2,2,2];
console.log(notsimilar.every((x,i,a) => a[i] === a[0]));
console.log(similar.every((x,i,a) => a[i] === a[0]));

Search and extract string in javascript array [duplicate]

This question already has answers here:
Filter strings in Array based on content (filter search value)
(6 answers)
Closed 6 years ago.
I have a array in javascript containing "aassd,v_value1,asadds,v_value2, asddasd...", and I need extract the values that begin with v_ in a new array.
I used the next function to get the values, but only get the first value.
function search (array,string) {
var arr= [];
for (var i=0; i<array.length; i++) {
if (array[i].match(string)){
arr.push(i)
return arr;
}
}
return -1;
}
search(array,'v_')
Thanks.
You should use .filter() method as below:
function search (array,string) {
return array.filter(function (val) {
return val.substr(0, string.length) === string;
});
}
The filter() method returns items of array which fulfills the condition in the callback function
I think below might work. Just string match and push to new array if found.
var arr = ['aassd','v_value1','asadds','v_value2','asddasd'];
var newArr = []
substring = "v_";
for (var i = 0; i < arr.length; i++) {
if (arr[i].search(substring) === 0) {
newArr.push(arr[i]);
}
}
alert(newArr);
function search (array,string) {
var arr= [];
for (var i=0; i<array.length; i++) {
//Do not use MATCH here as you need values that STARTS WITH "v_", match will give you values like this asdasdav_asdasda also.
if (array[i].startsWith(string)){
//instead of this
//arr.push(i)
//use this , the above will push the index, this will push the VALUE(as asked in the question)
arr.push(array[i])
//remove this: as this breaks on the first true condition , hence you get one value.
//return arr;
}
}
return arr;
}
The Mistakes
Do not use MATCH for it will return values with the pattern anywhere in the string.
Use startsWith instead
Return outside the loop as it ends the loop when it matches the first time and hence you get only the first item
You should push the value not the index as asked in the question. So do this arr.push(array[i])

Using indexOf method on array, getting all indexes and not just first [duplicate]

This question already has answers here:
How to find the indexes of all occurrences of an element in array?
(16 answers)
Closed 8 years ago.
Say that I have an array containing strings:
var array = ["test","apple","orange","test","banana"];
and some strings are exactly the same (test). Say that I want to get all the indexes in the array where the string test is located in the array and not just the first indexOf. Is there a nice solution to this problem that is as fast as possible and not using jQuery, I.E getting 0,2 as a result?
Thanks
You can use the builtin Array.prototype.forEach like this
var indices = [];
array.forEach(function(currentItem, index) {
if (currentItem === "test") {
indices.push(index);
}
});
console.log(indices);
Even better you can use Array.prototype.reduce like this
var indices = array.reduce(function(result, currentItem, index) {
if (currentItem === "test") {
result.push(index);
}
return result;
}, []);
console.log(indices);
Since you want the solution to be even working in IE, you might want to go with the plain old loop, like this
var indices = [], i;
for (i = 0; i < array.length; i += 1) {
if (array[i] === "test") {
indices.push(i);
}
}
console.log(indices);

Categories