I work on an Angular project and I built an array.
Now I'd like to rename one of the items of the array. I found the way to rename the keys of an array but I still don't know how to do to apply this to its values.
Here is my array below.
I'd like to change 'valueC' by 'valueZ'.
myArray = ['valueA', 'valueB', 'valueC']
I tried the following code :
for (const k in this.myArray) {
if (k == "valueC") {
this.myArray[k] = "valueZ";
}
But it does not work.
Could you help me ?
Any help would be very appreciated, thanks.
Below are two possible methods!
const myArray = ['valueA', 'valueB', 'valueC']
//rename - if index known
myArray[2] = 'valueZ';
console.log('if index known', myArray);
//rename - if index not known
const foundIndex = myArray.findIndex(x => x === 'valueC');
if (foundIndex > -1) {
myArray[2] = 'valueZ';
}
console.log('if index not known', myArray);
Your code just needs a minor correction:
if (this.myArray[k] == "valueC")
Try this:
const myArray = ['valueA', 'valueB', 'valueC'];
for (const k in myArray) {
if (myArray[k] == "valueC") {
myArray[k] = "valueZ";
}
}
console.log(myArray);
You need to track the index, easy with a forEach
this.myArray.forEach((k, index) => {
if (k == "valueC") {
this.myArray[index] = "valueZ";
}
})
My prefered way :
Though, be sure to have the value "valueC" inside the array
otherwise indexOf will return a -1, provoquing an error
// without index control
this.myArray[this.myArray.indexOf("valueC")] = "valueZ";
// with index control
const index = this.myArray.indexOf("valueC")
if (index >= 0) {
this.myArray[index] = "valueZ";
}
Also note this for future usage :)
for (const k in array) : in that case k is the index of elements in array
for (const k of array) : in that case k is the value of elements in array
On top of all the other solutions here, another approach, and one I believe is better in that it gets you in the mindset of immutability, is to return a new object instead of modifying the current one.
Ex:
this.myArray = this.myArray.map(x => {
if(x !== 'valueC')
return x;
return 'valueZ';
});
So map here will return a new array object for us, in this case a string array given your current array is a string array. Another pattern in use here is only checking for the negative case. Instead of having if/else or a chain of them, we know that for all case that aren't 'valueC' we retain their original value and only valueC's value needs to change to valueZ
Related
Currently I have a unidimensional array, e.g. ['thing1', 'cond1', 'thing2', 'cond2', 'thing3']
I would like to pair each item to create a new multidimensional array like so [['thing1', 'cond1'], ['thing2', 'cond2'], ['thing3']]. I don't mind the last item being ['thing3', undefined] – if anything this is preferable unless someone raises this as bad practice.
So far I have
const pair = (arr) => {
let paired = [];
for (i = 0; i < arr.length; i += 2) {
paired.push([arr[i], arr[i+1]]);
}
return paired;
}
You can try this out in my JS Bin example.
This works perfectly fine AFAIA but I'd love this to be as concise as possible using modern JS and I'm not as polished as I should be with my array manipulation.
Thanks in advance to everyone who gives this a go.
Let the challenge... BEGIN!
You could take a while loop with an index variable. For pushing a pair take slice.
const pair = array => {
let paired = [],
i = 0;
while (i < array.length) paired.push(array.slice(i, i += 2));
return paired;
}
var array = ['thing1', 'cond1', 'thing2', 'cond2', 'thing3'],
paired = pair(array);
console.log(paired);
You can try this regex. Group the values by finding the number by using regular expression.
const data = ['thing1', 'cond1', 'thing2', 'cond2', 'thing3'];
const result = {};
data.forEach(value => {
const index = value.replace(/[^\d.]/g, '');
if (typeof result[index] == 'undefined') {
result[index] = [];
}
result[index].push(value);
});
const array = Object.values(result);
console.log(array);
I have an Array and i would like to Filter or delete the following urls from my Array every time they appear:
"https://basueUrl.com/Claim"
"https://basueUrl.com/ExplanationOfBenefit"
My Array
Array= [
"https://basueUrl.com/Patient"
"https://basueUrl.com/Organization"
"https://basueUrl.com/Claim"
"https://basueUrl.com/Practitioner"
"https://basueUrl.com/Encounter"
"https://basueUrl.com/Condition"
"https://basueUrl.com/Claim"
"https://basueUrl.com/ExplanationOfBenefit"
"https://basueUrl.com/Claim"
"https://basueUrl.com/ExplanationOfBenefit"
"https://basueUrl.com/ExplanationOfBenefit"
]
First Solution I have tried for loop but did not work?
for( var i = 0; i < Array.length; i++){
if ( Array[i] === "https://basueUrl.com/ExplanationOfBenefit" & "https://basueUrl.com/Claim") {
Array.splice(i, 1);
i--;
}
}
console.log(Array);
Second Solution I tried making a remove method did not work either.
function arrayRemove(Array, value) {
return Array.filter(function(ele){
return ele != value;
});
}
var result = arrayRemove(Array,"https://basueUrl.com/ExplanationOfBenefit" & "https://basueUrl.com/Claim");
Any suggestion please?
The first approach is modifying the array while the loop is being executed, which generates problem with the index because the array.length changes when you call Array.prototype.splice.
In the second approach, you're not passing what you think
console.log("https://basueUrl.com/ExplanationOfBenefit" & "https://basueUrl.com/Claim");
// A number? probably you want an array.
You can use the function filter and the function includes as follow:
let skip = ["https://basueUrl.com/Claim", "https://basueUrl.com/ExplanationOfBenefit"];
let arr = ["https://basueUrl.com/Patient","https://basueUrl.com/Organization","https://basueUrl.com/Claim","https://basueUrl.com/Practitioner","https://basueUrl.com/Encounter","https://basueUrl.com/Condition","https://basueUrl.com/Claim","https://basueUrl.com/ExplanationOfBenefit","https://basueUrl.com/Claim","https://basueUrl.com/ExplanationOfBenefit","https://basueUrl.com/ExplanationOfBenefit"];
let result = arr.filter(url => !skip.includes(url));
console.log(result);
Array.filter(x => x !== "https://basueUrl.com/Claim" && x !== "https://basueUrl.com/ExplanationOfBenefit")
var Array= [
"https://basueUrl.com/Patient",
"https://basueUrl.com/Organization",
"https://basueUrl.com/Claim",
"https://basueUrl.com/Practitioner",
"https://basueUrl.com/Encounter",
"https://basueUrl.com/Condition",
"https://basueUrl.com/Claim",
"https://basueUrl.com/ExplanationOfBenefit",
"https://basueUrl.com/Claim",
"https://basueUrl.com/ExplanationOfBenefit",
"https://basueUrl.com/ExplanationOfBenefit"
];
var filteredArray = Array.filter(item => item !== "https://basueUrl.com/Claim" && item !== "https://basueUrl.com/ExplanationOfBenefit")
console.log(filteredArray)
You can run the code below. Hope this helps.
// use this array instead on the original. It creates a new array from the original
// array.
const newFilteredArray = Array.filter(url => url !== 'https://basueUrl.com/Claim' &&
url !== 'https://basueUrl.com/ExplanationOfBenefit');
Please see below the way you can achieve the above mentioned scenario.
arr.filter(ele=>ele!=="https://basueUrl.com/Claim"
&& ele!=="https://basueUrl.com/ExplanationOfBenefit");
function countUniqueItems(arr) {
nums = [];
for (i = 0; i < arguments.length; i++) {
const item = arr[i];
console.log(i);
//console.log(item);
if (nums.includes(arr) === true) {
//console.log('8 is in the array');
//nums.push(arr)
} else {
nums.push(arr);
//console.log('8 is NOT in the array');
//nums.push(item)
}
}
return nums;
}
countUniqueItems(1, 2);
So it will give back the first argument which is 1 but i want it to be able to say argument 2 and 3 and so on
So you need to pass an array into the function, in place of 1,2 pass [1,2].
Then inside your function, you should use arr.length in place of arguments.length.
Then you look at your logic for the loop, you are pushing atm arr into nums, but if you pass and array that isn't really want you want, you should be pushing item as that is the variable which represents your current element from the array.
It looks from you comments like you're trying to make a unique list of inputs. Perhaps something like this would do the trick.
EDIT: Updated to use arguments
function uniqueNumbers() {
let arrayOfArguments = [...arguments]
let uniqueNums = [];
arrayOfArguments.map(i => !uniqueNums.includes(i) ? uniqueNums.push(i) : null);
return uniqueNums;
};
console.log(uniqueNumbers(1,2,3,3));
you should either pass an array to countUniqueItems or use the arguments keyword in the for-loop.
Your code is only seeing 1 (as arr inside the function).
basic implementation to find unique items
function countUniqueItems(...arr) {
let nums = [];
for (let num of arr) {
if (nums.indexOf(num) === -1) nums.push(num);
}
return nums;
}
console.log(countUniqueItems(1, 2, 1));
Using Set you can remove the duplicate values, you dont need to do logic run the loop to find the unique values from array.
const a = [1,2,3,3];
const uniqueSet = new Set(a);
uniqueSet.size
let uniqueFinder = arr => { const uniqueSet = new Set(arr); return uniqueSet.size}
const arrywithduplicates = [1,2,3,3,4,4];
uniqueFinder(arrywithduplicates) // return 4
Read more about Set : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
This is a very simple question but I am not been able to wrap my head around it.
I have an array of pages with n number of page names, I want to run a loop with some page names not included in it.
var arr = ["page-name", "page-name-two", 'page-3', 'some-more', 'another-page'];
for (var page in arr) {
if (arr[page] !== "page-name" || arr[page] !== "some-more") {
console.log(arr[page])
}
}
Now the result that I want is this:
page-name-two
page-3
another-page
What am I doing wrong?
Just take logical AND && instead of logical OR ||.
Please use a for loop with a variable for the index instead of the keys of an object.
Source:
Why is using “for…in” with array iteration a bad idea?
var arr = ["page-name", "page-name-two", 'page-3', 'some-more', 'another-page'];
for (var i = 0; i < arr.length; i++) {
if (arr[i] !== "page-name" && arr[i] !== "some-more") {
console.log(arr[i]);
}
}
The expression
arr[i] !== "page-name" || arr[i] !== "some-more"
is always true, because for exampe if
arr[i] === "page-name"
then the other part is true, because of
"page-name" !== "some-more"`.
You should use .filter() to filter values from first array and then perform whatever action you want to perform on resultant array. This will save your from writing a lot of OR / AND conditions in case you need to filter more values.
let arr1 = ["page-name", "page-name-two", 'page-3', 'some-more', 'another-page'],
arr2 = ["page-name", 'some-more'];
let result = arr1.filter(s => !arr2.includes(s));
console.log(result);
I would store the values that you're looking to eliminate, then run Array.filter on your list of all page names to find matches. If a name matches, remove it from the final array.
// This can be a array of whatever strings you're looking to eliminate from the array
const valuesToFilter = ['page-name', 'some-more'];
// Your original array
const arr = ["page-name", "page-name-two", 'page-3', 'some-more', 'another-page'];
// Use Array.filter to eliminate anything that doesn't pass the filter test
const filteredArr = arr.filter(page => {
let foundMatch = false;
valuesToFilter.forEach(value => {
if (page === value) {
foundMatch = true;
}
})
if (!foundMatch) return page;
});
console.log(filteredArr);
I have an array of objects in javascript. I use jquery.
How do i get the first element in the array? I cant use the array index - as I assign each elements index when I am adding the objects to the array. So the indexes arent 0, 1, 2 etc.
Just need to get the first element of the array?
If you don't use sequentially numbered elements, you'll have to loop through until you hit the first one:
var firstIndex = 0;
while (firstIndex < myarray.length && myarray[firstIndex] === undefined) {
firstIndex++;
}
if (firstIndex < myarray.length) {
var firstElement = myarray[firstIndex];
} else {
// no elements.
}
or some equivalently silly construction. This gets you the first item's index, which you might or might not care about it.
If this is something you need to do often, you should keep a lookaside reference to the current first valid index, so this becomes an O(1) operation instead of O(n) every time. If you're frequently needing to iterate through a truly sparse array, consider another data structure, like keeping an object alongside it that back-maps ordinal results to indexes, or something that fits your data.
The filter method works with sparse arrays.
var first = array.filter(x => true)[0];
Have you considered:
function getFirstIndex(array){
var result;
if(array instanceof Array){
for(var i in array){
result = i;
break;
}
} else {
return null;
}
return result;
}
?
And as a way to get the last element in the array:
function getLastIndex(array){
var result;
if(array instanceof Array){
result = array.push("");
array.pop;
}
} else {
return null;
}
return result;
}
Neither of these uses jquery.
Object.keys(array)[0] returns the index (in String form) of the first element in the sparse array.
var array = [];
array[2] = true;
array[5] = undefined;
var keys = Object.keys(array); // => ["2", "5"]
var first = Number(keys[0]); // => 2
var last = Number(keys[keys.length - 1]); // => 5
I was also facing a similar problem and was surprised that no one has considered the following:
var testArray = [];
testArray [1245]= 31;
testArray[2045] = 45;
for(index in testArray){
console.log(index+','+testArray[index])
}
The above will produce
1245,31
2045,45
If needed you could exist after the first iteration if all that was required but generally we need to know where in the array to begin.
This is a proposal with ES5 method with Array#some.
The code gets the first nonsparse element and the index. The iteration stops immediately with returning true in the callback:
var a = [, , 22, 33],
value,
index;
a.some(function (v, i) {
value = v;
index = i;
return true;
});
console.log(index, value);
If you find yourself needing to do manipulation of arrays a lot, you might be interested in the Underscore library. It provides utility methods for manipulating arrays, for example compact:
var yourArray = [];
yourArray[10] = "foo";
var firstValue = _.compact(yourArray)[0];
However, it does sound like you are doing something strange when you are constructing your array. Perhaps Array.push would help you out?