How to slice value out of array in JS - javascript

I am trying to isolate the first value from an array that is constructed like below using JS:
[john,mike,tom]
I have tried the slice method but it is not working and I am assuming it's the way the array is constructed where the strings aren't enclosed in quotes. What would be the best way to transform the array above to either a string as a whole or a more properly formatted array so I can pull out any value I want?
edit For additional context, the array I mentioned above is the way is being passed to me from the source. I am trying to figure out how I can work with it to be able to slice up the values.
Sorry for the layman presentation of my question but I am still quite the beginner in JS and would appreciate it if anyone could help me out. Thanks!

In javascript, strings are enclosed in quotes. e.g.
'john', "mike" ect. so in order to create an array/list you need to put these values with quotes inside array and then access using index e.g.
var array = ['john', 'mike', 'tom']
console.log(array[0]); // john

Why do you need the strings to not have quotes? Is there an specific reason?
In js you need to put quotes on strings. If you try for example declaring an array in the way you did above the following will happen:
let x = [janaina,joao,julia]
VM203:1 Uncaught ReferenceError: janaina is not defined
at :1:10
So, correct way to delcare your array:
let x = ['janaina','joao','julia']
Now slice will work:
x.slice(0,1);
The result will be:
['janaina']

You can use the array prototype .shift(), but it will mutate your original array.
const john = {x: 124};
const mike = {x: 333};
const tom = {y: 355};
const slicy = [john, mike, tom].shift();
console.log(slicy);

Related

How to eliminate the values from array if it contains specific characters/string in JavaScript/lodash?

I am having one array with some values like below,
let a = ["Mango","1243greatApple","goodOrange","Watermelon","ThisGoodalsoberemoved","GreatOrange","Pappaya","BestApple"];
Now, I want to eliminate the values which contains string like Great and Good in the values.
Expecting output like below,
["Mango","Watermelon","Pappaya","BestApple"]
Tried using lodash, but it works only when it matches exact string. But i need it like regex match. Please help me out with this.
In vanilla JS, you can try with Array.prototype.filter()
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
And String.prototype.includes()
The includes() method determines whether one string may be found within another string, returning true or false as appropriate.
let a = ["Mango","1243GreatApple","GoodOrange","Watermelon","ThisGoodalsoberemoved","GreatOrange","Pappaya","BestApple"];
var r = a.filter(f => !(f.includes('Great') || f.includes('Good')));
console.log(r);

Can one convert a variable string to D3 data reference?

UPDATE:
I initially agreed that the answer provided in the "duplicate" question helped, but it didn't. This isn't a duplicate question because I am trying to convert the string into a column name to use with d as in using dynamic and multiple data. The answer provided still uses a string and references data statically as in Data[0]["myString"] but what I am looking for is d.MyColumnWhichUsedToBeAString
ORIGINAL:
I would like to take a string from an array and then use that value to find the corresponding csv data.
Is this possible? If so, how:
Example:
//Ultimately, I want to return d.one
var myArray = ["one", "two", "three"}
//Is there a a way to get d.one from the array. For example
d.myArray[0]
In Javascript you need to use the [] property accessor syntax for variable index names:
var theValue = d[myArray[0]]

Syntax Error In Javascript Object Declaration

I have declared an object like this
var me = {'alex','moore','baby','you'};
without the property names. I just want the elements to be set of strings. But i get error in both chrome dev-tools and firebug. i have googled but can't find any good answer.
What am i doing wrong?
thanks.
EDIT
Thanks for your answers. The reason am asking is that i am reading a book "Javascript: The Definitive Guide". On page 115 of the PDF file, it states that Javascript Objects ::
"They can also be used
(by ignoring the value part of the string-to-value mapping)
to represent sets of strings."
So i was trying to test it but getting errors. It seems the book is wrong that they can be used to represent sets of strings.
If you want an ordered list of values, then use an array ([]), not a plain object ({}).
var me = ['alex','moore','baby','you'];
Objects must have named properties.
var me = {
foo: 'alex',
bar: 'moore',
baz: 'baby',
etc: 'you'
};
Seems like what you are looking for is an array
var me = ['alex','moore','baby','you'];
Objects on the other hand need to have properties defined.
Square brackets
var me = ['alex','moore','baby','you'];
You should be using array not object.
var me = ['alex','moore','baby','you'];

understanding nested arrays in Javascript

I want to create a nested array in Javascript but can't do the thing what I want, I don't know if it is even possible. Here is an example of what kind of array I want to create:
var array = ['id1', 'id2', 'id3', 'id4'];
Then I want to add new array for each id such way that id values stayed the same. Why? because I want to use indexOf method to find out the element index of main array with sub array id. Something like this:
array[0]['par1'] should return the value of parameter1
array[0]['par2'] should return the value of parameter2
...
array[0] should return "id1" because
alert(array.indexOf("id1")) must return 0 ;
If there is some way of doing it, that would be great to know, but if it is not than I think I will use 2 arrays, one will hold sub arrays and another the ids
sorry for my bad English, I tried my best to explain my needs.
Maybe you want to do
array[0] = {par1: 'somevalue', par2: someother};
array[1] = {par1: 'anotehrone', par2: stillanother};
This sets as elements of you array javascript objects, here used as associative arrays. They enable you to set or get elements by key :
array[0]['par1'] = 'new value'; // write
var newval = array[0]['par1']; // read
But if you also want to have array[0] returning something that's not a generic object but a string... then you probably don't want javascript. This language just doesn't work like that.

How do I access the first key of an ‘associative’ array in JavaScript?

I have a js 'associative' array, with
array['serial_number'] = 'value'
serial_number and value are strings.
e.g. array['20910930923'] = '20101102'
I sorted it by value, works fine.
Let's say I get back the object 'sorted';
Now I want to access the first KEY of the 'sorted' array.
How do I do it? I can't think I need an iteration with
for (var i in sorted)
and just stop after ther first one...
thanks
edit: just to clarify, I know that js does not support associative arrays (that's why I put it in high commas in the Title).
2021 Update
Since ES6, properties with string keys are enumerated in insertion order. Here's a nice summary. My original answer from 2010 was correct at the time and is preserved below:
Original answer
JavaScript object properties are specified to have no order, much though many people wish it were different. If you need ordering, abandon any attempt to use an object and use an Array instead, either to store name-value objects:
var nameValues = [
{name: '20910930923', value: '20101102'},
{name: 'foo', value: 'bar'}
];
... or as an ordered list of property names to use with your existing object:
var obj = {
'20910930923': '20101102',
'foo': 'bar'
};
var orderedPropertyNames = ['20910930923', 'foo'];
Try this:
// Some assoc list
var offers = {'x':{..some object...}, 'jjj':{...some other object ...}};
// First element (see attribution below)
return offers[Object.keys(offers)[0]];
// Last element (thanks to discussion on finding last element in associative array :)
return offers[Object.keys(offers)[Object.keys(offers).length - 1]];
Actually JavaScript doesn't support associative arrays, so you can't loop through it in an implied order (e.g. you can't access it via the indexer property array[0] won't access the first element in your object). The syntax is what makes it look like it does, but in reality it doesn't. So you have no "Order" to your objects.
http://www.hunlock.com/blogs/Mastering_Javascript_Arrays
Javascript does not have, and does not
support Associative Arrays. However…
All arrays in Javascript are objects
and Javascript's object syntax gives a
basic emulation of an associative
Array. For this reason the example
code above will actually work. Be
warned that this is not a real array
and it has real pitfals if you try to
use it. The 'person' element in the
example becomes part of the Array
object's properties and methods, just
like .length, .sort(), .splice(), and
all the other built-in properties and
methods.
Just thinking off the top of my head, but could you have another array with the key value pairs swapped?
So the answer would be arrayKeyValueReversed['20101102'] = '20910930923';
When you sort the array, use the first item (array[0]) as the key to get the value in the arrayKeyValueReversed.

Categories