I have the following function which is supposed to remove the smallest value from an array, but if this is a duplicate it will just remove the first one and leave the others.
var array1 = [1, 2, 3, 4, 5];
var array2 = [5, 3, 2, 1, 4];
var array3 = [2, 2, 1, 2, 1];
function removeSmallest(numbers) {
return numbers.filter(function(elem, pos, self) {
if(elem == Math.min.apply(null, numbers) && pos == self.indexOf(elem)) {
// Remove element from Array
console.log(elem, pos);
numbers.splice(pos, 1);
};
return numbers;
});
};
Via console.log(elem, pos) I understand that I have correctly identified the smallest and first element in the array, but when I try to remove it through splice(), I end up getting the following result for the arrays:
array1 = [1, 3, 4, 5]; // But I expected [2, 3, 4, 5]
array2 = [5, 3, 2, 1]; // But I expected [5, 3, 2, 4]
array3 = [2, 2, 1, 1]; // But I expected [2, 2, 2, 1]
Do you know what is the issue with my code? Thanks in advance for your replies!
function removeSmallest(numbers) {
const smallest = Math.min.apply(null, numbers);
const pos = numbers.indexOf(smallest);
return numbers.slice(0, pos).concat(numbers.slice(pos + 1));
};
You shouldn't use filter() the way you do. It's also a good practice that a function should return a new array rather than modifying the existing one and you definitely shouldn't modify an array while iterating over it.
function removeSmallest(arr){
var temp=arr.slice(),smallElement=null;
temp.sort(sortReverse);
smallElement=temp[temp.length-1];
var position=arr.indexOf(smallElement);
arr.splice(pos,1);
console.log(arr);
}
function sortReverse (a,b){
if(a<b){return 1}
else if(a>b){return -1;}
else{return 0;}
}
var array1 = [1, 2, 3, 4, 5];
removeSmallest(array1);
Related
I have an array like this :
const arr = [1, 2, 3, 4, 5];
And I want to shift all the values and remove the last value and put 0.
My array should look like this after the operation :
[2, 3, 4, 5, 0]
How to do this ?
here is one approach
const arr = [1, 2, 3, 4, 5];
arr.shift()
arr.push(0)
console.log(arr)
second approach
const arr = [1, 2, 3, 4, 5];
v=arr.slice(1,arr.lenth)
console.log([...v,0])
In case someone finds this useful in java. Note - this approach will manipulate the original array
private void circularArray(int originalArray[]) {
for (int i = 0; i < originalArray.length -1; i++) {
originalArray[i] = originalArray[i+1];
}
originalArray[originalArray.length -1] = 0;
}
I need to create a new array made up of unique elements from two separate arrays.
I have converted both arrays into a single array and then converted this into an object to check the frequency of the elements. If the value of an object property is 1 (making it a unique property), I want to return it to an array (minus the value). Is there a straightforward way to achieve this?
Edits: Moved result outside for loop. Expected output should be [4]
function diffArray(arr1, arr2) {
var finalArr = [];
var countObj = {};
var newArr = [...arr1, ...arr2];
for (var i = 0; i < newArr.length; i++) {
if (!countObj[newArr[i]]) countObj[newArr[i]] = 0;
++countObj[newArr[i]];
}
for (var key in countObj) {
if (countObj[key] === 1) {
finalArr.push(key);
}
} return finalArr;
}
diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);
If I understand correctly, you're wanting to find the difference between arr1 and arr2, and returns that difference (if any) as a new array of items (that are distinct in either array).
There are a number of ways this can be achieved. One approach is as follows:
function diffArray(arr1, arr2) {
const result = [];
const combination = [...arr1, ...arr2];
/* Obtain set of unique values from each array */
const set1 = new Set(arr1);
const set2 = new Set(arr2);
for(const item of combination) {
/* Iterate combined array, adding values to result that aren't
present in both arrays (ie exist in one or the other, "difference") */
if(!(set1.has(item) && set2.has(item))) {
result.push(item);
}
}
return result;
}
console.log(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]), " should be [4]");
console.log(diffArray([1, 2, 3, 5, 8], [1, 2, 3, 5]), " should be [8]");
console.log(diffArray([1, 2, 3, 5, 8], [1, 2, 3, 5, 9]), " should be [8, 9]");
console.log(diffArray([1, 2], [1, 2]), " should be []");
Basic question on .splice() method, and how best to remove an element from an array.
I want to remove an item from an array with .splice() but when I do, I want to have the original array minus the removed element returned. .splice() returns the removed element instead.
var arr = [1, 2, 3, 4, 5, 6, 7]
var newArr = arr.splice(3, 1)
console.log(newArr) // [4]
// whereas I want [1, 2, 3, 5, 6, 7]
What's the best, and most eloquent way to do this?
Using the spread operator, you can do:
var arr = [1,2,3,4,5,6],
indexToRemove = 3,
newArr = [
...arr.slice(0,indexToRemove),
...arr.slice(indexToRemove+1)
]
Or if you want to use ES5, it can look something like:
var arr = [1,2,3,4,5,6],
indexToRemove = 3,
newArr = [].concat(arr.slice(0,indexToRemove)).concat(arr.slice(indexToRemove+1))
.splice mutates the array in place and returns the removed elements. So unless you actually need a function that returns the array itself, just access arr:
var arr = [1, 2, 3, 4, 5, 6, 7]
arr.splice(3, 1)
console.log(arr) // [1, 2, 3, 5, 6, 7]
You can create a wrapper function that performs the splice and returns the array:
function remove(arr, index) {
arr.splice(index, 1)
return arr;
}
var newArr = remove(arr, 3);
// Note: `newArr` is not a new array, it has the same value as `arr`
If you want to create a new array, without mutating the original array, you could use .filter:
var newArr = arr.filter(function(element, index) {
return index !== 3;
}); // [1, 2, 3, 5, 6, 7]
arr; // [1, 2, 3, 4, 5, 6, 7]
It seems correct for me, but it doesn't work:
var arr = [1, 2, 3, 4, 5];
var bar = [2, 4];
arr = arr.filter(function(v) {
for (var i; i < bar.length; i++) {
return bar.indexOf(v);
}
});
console.log(arr); // []
// expected: [1, 3, 5]
How this will work, and how to do the same work with map?
Array#filter iterates over the array, you don't need for inside filter
The problem with for inside filter is that it'll return the index of the element, which could be -1(truthy) if not found and anything upto the length of array. And only for the first element i.e. index zero, filter will not add the element as zero is falsey in JavaScript.
Also, the for loop will only check if the first element of the bar and return from there.
var arr = [1, 2, 3, 4, 5];
var bar = [2, 4];
arr = arr.filter(function(v) {
return bar.indexOf(v) === -1;
});
console.log(arr);
document.write('<pre>' + JSON.stringify(arr, 0, 4) + '</pre>');
You don't need Array#map, map will transform the array elements with keeping the same number of elements.
ES6:
Since ES6 you can use Array#includes, and arrow functions to make your code look cleaner:
let arr = [1, 2, 3, 4, 5];
let bar = [2, 4];
arr = arr.filter(v => !bar.includes(v));
console.log(arr);
document.write('<pre>' + JSON.stringify(arr, 0, 4) + '</pre>');
When I want to remove one element, it is easy. This is my function:
function removeValues(array, value) {
for(var i=0; i<array.length; i++) {
if(array[i] == value) {
array.splice(i, 1);
break;
}
}
return array;
}
But how do I remove multiple elements?
Here a simple version using ES7:
// removing values
let items = [1, 2, 3, 4];
let valuesToRemove = [1, 3, 4]
items = items.filter((i) => !valuesToRemove.includes(i))
For a simple version for ES6
// removing values
let items =[1, 2, 3, 4];
let valuesToRemove = [1, 3, 4]
items = items.filter((i) => (valuesToRemove.indexOf(i) === -1))
const items = [0, 1, 2, 3, 4];
[1, 4, 3].reverse().forEach((index) => {
items.splice(index, 1)
})
// [0, 2, 4]
I believe you will find the kind of functionality you are looking for in Javascript's built in array functions... particularily Array.map(); and Array.filter();
//Array Filter
function isBigEnough(value) {
return value >= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]
//Array Map (Can also be used to filter)
var numbers = [1, 4, 9];
var doubles = numbers.map(function(num) {
return num * 2;
});
// doubles is now [2, 8, 18]. numbers is still [1, 4, 9]
/////UPDATE REFLECTING REMOVAL OF VALUES USING ARRAY MAP
var a = [1,2,3,4,5,6];
a.map(function(v,i){
if(v%2==0){
a.pop(i);
}
});
console.log(a);
// as shown above all array functions can be used within the call back to filter the original array. Alternativelty another array could be populated within the function and then aassigned to the variable a effectivley reducing the array.