Does splicing of an array reduce the value of array.length? [duplicate] - javascript

This question already has answers here:
Remove items from array with splice in for loop [duplicate]
(5 answers)
Closed 3 years ago.
function filter_list(l) {
for (var i = 0; i < l.length; i++) {
if (typeof(l[i]) === 'string') {
l.splice(i, 1);
}
}
return l;
}
console.log(filter_list([1, 2, 'a', 'b']));
When element 2 (index starts with 0) is spliced why doesn't the length of the array in the for loop change to 3? The last element should not be processed but it is processed.

Does splicing of an array reduce the value of array.length?
Yes, because splice method modifies the array inplace
The solution could be using a while loop.
function filter_list(l) {
i = l.length;
while (i--) {
if (typeof(l[i]) === 'string') {
l.splice(i, 1);
}
}
return l;
}
console.log(filter_list([1, 2, 'a', 'b']));

Related

string conversion to numbers to avoid dupes [duplicate]

This question already has answers here:
Get all unique values in a JavaScript array (remove duplicates)
(91 answers)
How to convert a string to an integer in JavaScript
(32 answers)
Closed 1 year ago.
function removeDups(arr) {
let x = {};
for (let i=0; i<arr.length; i++) {
if(!x[arr[i]]) {
x[arr[i]] = true;
}
}
let result = Object.keys(x);
for(let i=0; i<result.length; i++) {
if(typeof result[i] == Number) {
result[i] = parseInt(result[i]);
}
}
return result;
}
removeDups([1, 0, 1, 0]);
//➞ [1, 0]
Hey guys trying to return [1,0] like the problem states but I keep returning ['1','0']. I'm trying to convert these values to numbers and not having much luck. Any help?

Trying to use.splice to remove duplicates in JavaScript [duplicate]

This question already has answers here:
When looping through values of a JS array, and I remove value, do I need to use while instead of for?
(5 answers)
Closed 1 year ago.
I am trying to make a function that removes the duplicate array elements from an array and returns the same array with no duplicates. I figured this would work:
var removeDuplicates = function(nums) {
nums.sort(function(a,b){ return a-b;});
let len = nums.length;
for (let i = 0; i < nums.length; i++){
if (nums[i] === nums[i+1]){
nums.splice(i,1);
}
}
return nums;
};
console.log(removeDuplicates([0,0,1,1,1,2,2,3,3,4]));
However the console log at the bottom returns nums as [0,1,1,2,3,4] and not the [0,1,2,3,4] I was expecting. Is there any way to modify the for loop or use splice differently (or maybe some other array method that does not return a new array) to remove that last 1 duplicate?
You need to decrement the index because the element above it will be shifted into the current index.
var removeDuplicates = function(nums) {
nums.sort(function(a,b){ return a-b;});
let len = nums.length;
for (let i = 0; i < nums.length; i++){
if (nums[i] === nums[i+1]){
nums.splice(i,1);
--i;
}
}
return nums;
};
console.log(removeDuplicates([0,0,1,1,1,2,2,3,3,4]));
Alternatively, looping backwards avoids this issue altogether.
var removeDuplicates = function(nums) {
nums.sort(function(a,b){ return a-b;});
let len = nums.length;
for (let i = nums.length - 1; i >= 0; i--){
if (nums[i] === nums[i+1]){
nums.splice(i,1);
}
}
return nums;
};
console.log(removeDuplicates([0,0,1,1,1,2,2,3,3,4]));
A simpler method would be to use a Set.
var removeDuplicates = function(nums) {
return [...new Set(nums.sort((a,b)=>a-b))];
};
console.log(removeDuplicates([0,0,1,1,1,2,2,3,3,4]));

i have problem with converting the indexOf to a for loop and because of that i am having wrong answers [duplicate]

This question already has answers here:
Looping through array and removing items, without breaking for loop
(17 answers)
Closed 3 years ago.
Here is the question
Q) take 2 arrays and pass it to a function, then check if the square of the array1 is contained in the array2 (Note: Order doesn't matter, also 2 duplicates in arr1[1,2,2], there should be 2 duplicates in arr2[1,4,4]).
I have this code in which, i am trying to convert the indexOf to a for loop and i have included that code which i tried after this code
function same2(arr1, arr2){
if (arr1.length !== arr2.length){
return false;
}
for (let i = 0; i < arr1.length; i++){
let currentIndex = arr2.indexOf(arr1[i] ** 2);
// if the square of arr1 is contained in any of the index in arr2
if (currentIndex === -1){
return false;
}
console.log(arr2);
arr2.splice(currentIndex, 1);
}
return true;
}
same2([10,2, 3, 5], [100, 4, 25, 9]);
Here is the code with 2 for loop and its giving wrong output for the corresponding input.
function same(arr1, arr2){
if (arr1.length !== arr2.length){
return false;
}
for (let i = 0; i < arr1.length; i++){
for (let j = 0; j < arr2.length; j++){
let currentIndex = arr1[i] ** 2;
console.log(currentIndex);
if (currentIndex === -1){
return false;
}
if (arr2[j] === currentIndex){
arr2.splice(currentIndex, 1);
// console.log(arr2);
}
}
}
return true;
}
same([1, 10,2, 4], [10, 1, 16, 4]);
I know i have problem with the index of the array, but i am not able to break it.
What about this functional approach?
test2 = (i1, i2) => i1.length === i2.length && i1.reduce((a,c) => a && i2.includes(c*c), 1)
console.log(test2([1,2,3],[1,4,9]))
Update 1
Here is a double loop approach, but somehow different from yours as you have several things wrong there. First of all: with splice you are modifying the array for which you have a for loop - that is something you should never do. Secondly, you have recalculated the value you are looking for in the inner loop - that made it absolutelly unusable. You don't need that variable at all, but I have used it to be more straightforward.
Update 2
If you want to have an element in arr2 to count only once, you can introduce the trick to remove that element - without modifying the array with splice.
function same(arr1, arr2){
if (arr1.length !== arr2.length){
return false;
}
for (let i = 0; i < arr1.length; i++){
let lookFor = arr1[i] ** 2;
let found = false;
for (let j = 0; j < arr2.length; j++){
if (arr2[j] === lookFor){
delete arr2[j]
found = true
break;
}
}
if(!found) return false
}
return true;
}
console.log(same([1,2,2],[1,4,4]))
console.log(same([1,2,2],[1,1,4]))

Javascript: destructive array.filter()? [duplicate]

This question already has answers here:
javascript - remove array element on condition
(11 answers)
Closed 4 years ago.
Is there a good functional style way of deleting elements in a JS array while looping?
I know filter can be used to create a new array:
var newArr = arr.filter((x) => x.foo > bar)
But is there a way to actually delete the elements from arr as you go?
BTW: I can't reassign, this is a data object on Vue component, so I need to update, not reassign.
BTW2: This is not a duplicate. I know how to do it with normal JS iteration. I am looking for a functional way, and the referenced answer doesn't contain that. Not a dupe.
Simply re-assign the Array
let arr = [1,2,3,4,5];
arr = arr.filter(v => v < 3);
console.log(arr);
If you can't re-assign, use a loop and Array.splice. Note that for every deleted item, the index should be decremented by 1.
const arr = [1,2,3,4,5];
for (let i = 0; i < arr.length; i += 1) {
if (arr[i] < 3) {
arr.splice(i, 1);
// you should decrement the index (i) now
i -= 1;
}
}
console.log(arr);
Why not simply do this
arr = arr.filter((x) => x.foo > bar)
UPDATE:
We can splice the unwanted item from the array while iterating, if you do not want to re-assign.
Does this answer your question?
for(let i = 0; i < arr.length; i++) {
if (arr[i].x > bar) arr.splice(idx, 1);
}

calculate the sum of a list of lists [duplicate]

This question already has answers here:
Javascript unlimited nested array handling
(6 answers)
Closed 8 years ago.
I found this code on http://games.usvsth3m.com/javascript-under-pressure/ and I reach the 5th problem which requires to estimate the sum of all the integer in the list. The list may contains nested lists. So for a list [1,2,3,4,5] or [[1,2,3],4,5] the code below works but for a list [[[[[1]]]],2,3,4] does not. I try a lot of hours and I do not know to solve it. I need a hit plz.
function arraySum(i) {
var sum =0;
for (var id =0; id<i.length;id++){
if(typeof i[id]==='object'){
var ar = i[id];
for (var dd =0; dd<ar.length;dd++ ){
if(typeof ar[dd]==='number'){
sum+=parseInt(ar[dd]);
}
}
}
else
if(typeof i[id]==='number'){
sum+=parseInt(i[id]);
}
}
return sum;
}
use recursion.
var arr = [1, 2, [3, 4, [[[5]]]]];
num = 0;
function loop (arr) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] instanceof Array) {
loop(arr[i]);
} else {
num += parseInt(arr[i]);
}
}
}
loop(arr);
console.log(num);
fiddle - http://jsfiddle.net/9j1hcx4x/

Categories

Resources