I am trying to get the first and last item in array and display them in an object.
What i did is that I use the first and last function and then assign the first item as the key and the last item as the value.
var myArray = ['Rodel', 'Mike', 'Ronnie', 'Betus'];
function firstAndLast(array) {
var firstItem = myArray.first;
var lastItem = myArray.last;
var objOutput = {
firstItem : lastItem
};
}
var display = transformFirstAndLast(myArray);
console.log(display);
however this one gets me into trouble. It says undefined. Any idea why is that?
I've modified your code :
var myArray = ['Rodel', 'Mike', 'Ronnie', 'Betus'];
function firstAndLast(array) {
var firstItem = myArray[0];
var lastItem = myArray[myArray.length-1];
var objOutput = {
first : firstItem,
last : lastItem
};
return objOutput;
}
var display = firstAndLast(myArray);
console.log(display);
UPDATE: New Modification
var myArray = ['Rodel', 'Mike', 'Ronnie', 'Betus'];
function firstAndLast(array) {
var firstItem = myArray[0];
var lastItem = myArray[myArray.length-1];
var objOutput = {};
objOutput[firstItem]=lastItem
return objOutput;
}
var display = firstAndLast(myArray);
console.log(display);
With ES6 and destructuring:
const myArray = ['Rodel', 'Mike', 'Ronnie', 'Betus'];
const { 0: first, length, [length -1]: last } = myArray //getting first and last el from array
const obj = { first, last }
console.log(obj) // { first: "Rodel", last: "Betus" }
ES6
var objOutput = { [myArray[0]]: [...myArray].pop() }
var myArray = ['Rodel', 'Mike', 'Ronnie', 'Betus'];
var objOutput = { [myArray[0]]: [...myArray].pop() }
console.log(objOutput);
As of 2021, you can use Array.prototype.at()
let colors = ['red', 'green', 'blue']
let first = colors.at(0) // red
let last = colors.at(-1) // blue
To read more about Array.prototype.at()
I prefer using a simple array filter:
const myArray = ['one', 2, 3, 4, 5];
const filterFirstLast = (e, i, a) => i === 0 || i === a.length - 1;
const [ first, last ] = myArray.filter(filterFirstLast);
console.log(first, last); // outputs: 'one', 5
// dealing with insufficient input is another topic (input array length < 2)
console.log(['one'].filter(filterFirstLast )); // outputs: ['one']
console.log([].filter(filterFirstLast )); // outputs: []
transforming to something else is as easy
const obj = { [first]: last }; // will be: { one: 5 }, but never { one: "one" }
// OR, if you allow ['one'] to apply for both, if last is nullish (e.g. undefined, null, ""):
const obj = { [first]: last || first }; // will be: { one: 5 }, can be { one: "one" }
Another variation of roli answer
function firstAndLast(array) {
return { [[...array].shift()]: [...array].pop() };
}
To make your first and last properties work as you want, define them as properties with "getters" on the array prototype.
(You also have an inconsistency between firstAndLastArray and transformFirstAndLast, which needed to be fixed.)
Returning {firstName: lastName} will not do what you presumably want, since it will yield the key firstName. To use the actual first name as the key, use computed property names ({[firstName]: lastName}).
Object.defineProperties(Array.prototype, {
first: { get() { return this[0]; }},
last: { get() { return this[this.length - 1]; }}
});
var myArray = ['Rodel', 'Mike', 'Ronnie', 'Betus'];
function firstAndLast(array) {
var firstItem = myArray.first;
var lastItem = myArray.last;
return {[firstItem]: lastItem};
}
var display = firstAndLast(myArray);
console.log(display);
Or, much more simply, just
function firstAndLast(array) {
return {[array[0]]: array[array.length - 1]};
}
If you don't want to, or cannot, use computed property names, then
function firstAndLast(array) {
var result = {};
result[array[0]] = array[array.length - 1];
return result;
}
Do like this :-
var myArray = ['Rodel', 'Mike', 'Ronnie', 'Betus'];
function firstAndLast(myArr) {
var firstItem = myArr[0];
var lastItem = myArr[myArr.length - 1];
var objOutput = {};
objOutput[firstItem] = lastItem;
return objOutput;
}
var display = firstAndLast(myArray);
console.log(display);
well, I have another idea... for ex.:
const all = ['food', 'clean', 'cat', 'shower', 'work out']
console.log(`you have ${all.length} all!`)
console.log(`Todo: ${all[0]}`)
console.log(`Todo: ${all[all.length - 1]}`)
try this to find out first and last value of an array
var array = ['Rodel', 'Mike', 'Ronnie', 'Betus'];
let {0 : a ,[array.length - 1] : b} = array;
var objOutput = {
first : a,
last:b
};
console.log(objOutput)
In Array :- Check first and last element in array are same or not..
function hasSame(arr1, arr2) {
for(i=0; i <arr1.length ; i++) {
for(j=0; j <arr2.length ; j++) {
if(arr1[0] === arr2[0] && arr1[2] === arr2[2]) {
return true
} else
return false;
}
}
}
console.log(hasSame(
["white bread", "lettuce", "toast"],
["white bread", "tomato", "toast"]
))
Related
New to JS object and I just need someone to explain to me, why the object property becomes true when adding a duplicate value from an array. Below is my example using forEach()or reduce() method in removing duplicates. The undefined's makes sense to me. Only the true's, that I don't understand yet.
const names = ['James','John', 'James','Bob','John','Steve', 'James']
let unique = {};
names.forEach(el => {
console.log(unique[el])
if (!unique[el]) unique[el] = true;
});
console.log result inside forEach():
/*
unique['James'] = undefined
unique['John'] = undefined
unique['James'] = true
unique['Bob'] = undefined
unique['James'] = true
unique['Steve'] = undefined
unique['James'] = true
*/
console.log(Object.keys(unique)); // [ 'James', 'John', 'Bob', 'Steve' ]
Same in using reduce()method:
Object.keys(names.reduce((a,v) => {
if(!a[v]) a[v] = true;
return a;
},{}))
// [ 'James', 'John', 'Bob', 'Steve' ]
firstly it undefined, it looks like
first circle
console.log(unique["James"]) // undefined
if (!unique["James"]) { unique["James"] = true; } // it creates { James: true }
second circle ("James" already exists)
console.log(unique["James"]) // true
// if statement doesn't work
Here are simple examples of solving
const names = ['James','John', 'James','Bob','John','Steve', 'James'];
// example for array
let uniqueArray = [];
for(i=0; i < names.length; i++) {
if(uniqueArray.indexOf(names[i]) === -1) {
uniqueArray.push(names[i]);
}
}
console.log(uniqueArray)
// example for object
const uniqueObject = {};
names.forEach(el => uniqueObject[el] = true);
console.log(uniqueObject)
uniqueArray = Object.keys(uniqueObject)
console.log(uniqueArray)
I count the words in a paragraph by frequency of occurrences now I need to sort them too for example [this : 2, is : 3, it : 1] to [is : 3, this : 2, it : 1]. I divided keys and values into two different arrays then I sorted an array of values now I want to sort an array of keys
console.log('app running');
function getFrequencyOfWord(word : string) {
let counting: any = {};
let wordSplit: any = word.split(' ');
wordSplit.forEach(function (word: any) {
if (counting[word]) {
counting[word]++;
}
else {
counting[word] = 1;
}
})
var arr1 = Object.keys(counting);
var arr2 = arr1.map((suboor)=> {
return counting[suboor];
});
for (var i : number = 0; i < arr2.length; i++) {
for (var j = 0; j < (arr2.length -i -1); j++) {
if (arr2[j] > arr2[j+1]) {
const lesser = arr2[j+1];
arr2[j+1] = arr2[j];
arr2[j] = lesser;
}
}
}
console.log(arr2);
console.log(arr1);
}```
You could try something like the following:
let word = "moo moo moo hello one two three one";
let wordSplit = word.split(' ');
var counting = [];
wordSplit.forEach(function (word) {
if (counting[word]) {
counting[word]++;
}
else {
counting[word] = 1;
}
})
console.log("Counting ...");console.log(counting);
function swap(json){
var ret = {};
for(var key in json){
let element = ret[json[key]] ;
//console.log("element");console.log(element);
if(element == undefined){
ret[json[key]] = element= [];
}
element.push(key);
//console.log("element");console.log(element);
}
return ret;
}
let result = swap(counting);
console.log("RESULT ...");console.log(result);
var finalResult = [];
for(var key in result){
finalResult = finalResult.concat(result[key]);
}
console.log("Final RESULT ...");console.log(finalResult);
Output
Word Count:
[moo: 3, hello: 1, one: 2, two: 1, three: 1]
Result:
{1: Array(3), 2: Array(1), 3: Array(1)}
1: (3) ["hello", "two", "three"]
2: ["one"]
3: ["moo"]
Final Result
0: "hello"
1: "two"
2: "three"
3: "one"
4: "moo"
Fiddle: https://jsfiddle.net/menelaosbgr/xe9u7mqk/33/
Update
The problem is that you actually have a map of object instead of an array. An array of objects would be something like [{is:3},{this:2},{it:1}] . It's not that difficult to do the conversion. However, I think it's better to have objects that are like this {word:X, count:x}. See below:
let word = "this this is is it is";
let wordSplit = word.split(' ');
var counting = [];
wordSplit.forEach(function (word) {
if (counting[word]) {
counting[word]++;
}
else {
counting[word] = 1;
}
})
console.log("Counting ...");console.log(counting);
function swap(json){
var ret = {};
for(var key in json){
let element = ret[json[key]] ;
//console.log("element");console.log(element);
if(element == undefined){
ret[json[key]] = element= [];
}
element.push({count:json[key], word:key});
//console.log("element");console.log(element);
}
return ret;
}
let result = swap(counting);
console.log("RESULT ...");console.log(result);
//Reverse it and make it into objects...
let reversedResult = Object.assign([], result ).reverse();
console.log("RESULT-REVERSED ...");console.log(reversedResult);
//Final Conatenated Array
var concatenatedArray = [];
for(var key in reversedResult){
concatenatedArray = concatenatedArray.concat(reversedResult[key]);
}
console.log("CONCATENATED-ARRAY ...");console.log(concatenatedArray);
Result:
0: {count: 3, word: "is"}
1: {count: 2, word: "this"}
2: {count: 1, word: "it"}
Fiddle: https://jsfiddle.net/menelaosbgr/xe9u7mqk/49/
This is not possible to sort array of keys according to array of values but you can do something to map right key to right value by checking if(arr[key] == arr[value]) and if key and value are equal then you can push that key value pair into new array.
I am trying to convert an object literal into an array of arrays by using a function.
Using the two sample objects I have, the end result I'm looking for would be:
[ ["ugh","grr"] , ["foo", "bar"] , ["blah" , 138] ] from obj1
[ "shambala","walawala"] , ["foofighter","Barstool"] , ["blahblah",1382342453] ] from obj2
var obj1 = {
ugh: "grr",
foo: "Bar",
blah: 138
};
var obj2 = {
shambala: "walawala",
foofighter: "Barstool",
blahblah: 1382342453
};
var piece1 = Object.keys(obj1);
var piece2 = Object.values(obj1);
var result = [ ];
for (var i = 0; i < piece1.length; i++) {
result.push([piece1[i] , piece2[i]])
}
console.log(result)
From what I have above, I have been able to achieve:
[ ["ugh","grr"] , ["foo", "bar"] , ["blah" , 138] ] from obj1
But I am stumped about how to achieve the same output via a function.
This seems like a simple thing.
function objToArray(objectLiteral) {
var piece1 = Object.keys(objectLiteral);
var piece2 = Object.values(objectLiteral);
var result = [ ];
for (var i = 0; i < piece1.length; i++) {
return result.push([piece1[i] , piece2[i]])
}
}
console.log(objToArray(obj1))
This is what the best I can do but I keep on getting 1 and I don't know why.
Other attempts I just end up with undefined.
The problem with your code is you're using the return earlier than needed, see this working code:
var obj1 = {
ugh: "grr",
foo: "Bar",
blah: 138
};
var obj2 = {
shambala: "walawala",
foofighter: "Barstool",
blahblah: 1382342453
};
function objToArray(objectLiteral) {
var piece1 = Object.keys(objectLiteral);
var piece2 = Object.values(objectLiteral);
var result = [];
for (var i = 0; i < piece1.length; i++) {
result.push([piece1[i], piece2[i]])
}
return result;
}
console.log(objToArray(obj1));
If it's supported in your environment, you could use Object.entries:
var obj1 = {
ugh: "grr",
foo: "Bar",
blah: 138
};
var pairs = Object.entries(obj1);
Alternatively, you could write an entries function like this:
function entries(object) {
const pairs = [];
for(let key in object) {
if(object.hasOwnProperty(key)) {
pairs.push([key, object[key]]);
}
}
return pairs;
}
Here's how I'd implement it.
function objectToArray(obj) {
return Object.keys(obj).map(function(prop) {
return [prop, obj[prop]];
});
}
// ES2015
function objectToArray (obj) {
return Object.keys(obj).map(prop => [prop, obj[prop]]);
}
View demo
I have one array
var ar=['aa','cc','po']
I want to push objects in new array after checking the value of given array .In other words
I have these given conditions
var ar=['aa','cc','po']
var arr =[{name:"po"},{name:'aa'},{name:'cc'}];
Expected Output in new Array
[{name:'aa'},{name:'cc'},{name:"po"}]
As "aa" in in 0 index then I added object whose name property aa.
I try like this .but I used two for look .is there any simple way to do this
FIDDLE
var newArr=[];
for(var i=0;i<ar.length ;i++){
var text =ar[i];
for(var j=0;j<arr.length ;j++){
var obj =arr[j];
console.log(obj.name);
/*if(obj.name===text){
newArr.push(obj);
}*/
}
}
console.log(newArr);
This is a proposal in two part, first build an object with the reference to the items of arr and the create a new array with the given items of ar.
var ar = ['aa', 'cc', 'po'],
arr = [{ name: "po" }, { name: 'aa' }, { name: 'cc' }],
object = Object.create(null),
result = [];
arr.forEach(function (a) {
object[a.name] = a;
});
ar.forEach(function (a) {
object[a] && result.push(object[a]);
});
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
Using forEach iterator and generate object reference based on name and then generate result array using map()
var ar = ['aa', 'cc', 'po']
var arr = [{
name: "po"
}, {
name: 'aa'
}, {
name: 'cc'
}];
var ref = {};
// generating object reference with name property
arr.forEach(function(v) {
ref[v.name] = v;
});
// generating result array
// or you can use forEach as #NinaScholz answer
var res = ar.map(function(v) {
return ref[v];
}).filter(function(v) { // use filter to avoid null values , in case of missing elements
return v != null;
});
document.write('<pre>' + JSON.stringify(res, null, 3) + '</pre>');
Try this:
function convert(source) {
var
obj = [],
i;
for (i = 0; i < source.length; ++i) {
obj.push({name: source[i]});
}
return obj;
}
convert(['aa', 'bb', 'cc']); // [{name:'aa'},{name:'bb'},{name:'cc'}]
This would work if you want to assign values from array in sequence:
var ar=['aa','cc','po']
var arr =[{name:"po"},{name:'aa'},{name:'cc'}];
arr.map(function(obj,key){
obj.name = ar[key];
});
console.log(arr);
Do like this
var ar = ['aa', 'cc', 'po']
var arr = [{ name: "po"}, { name: 'aa'}, { name: 'cc'}];
$.each(ar, function(i, v) {
arr[i].name = v;
});
console.log(arr)
Fiddle
var array=['a','b','c'];
var arrayObj=[];
for(var i=0;i<array.length;i++){
var obj={};
obj.name=array[i];
arrayObj.push(obj);
}
console.log(JSON.stringify(arrayObj));
Output:
[{"name":"a"},{"name":"b"},{"name":"c"}]
I guess this is one very functional way of doing this job with no more than an assignment line. However Anoop Joshi's answer is more elegant provided that the ar array is shorter than equal to in length to the arr array.
var arr = ['aa','cc','po'],
ar = [{name:"po"},{name:'aa'},{name:'cc'}],
res = arr.map(e => ar[ar.findIndex(f => f.name == e)]);
document.write("<pre>" + JSON.stringify(res) + "</pre>");
I am looking for a solution, to push/convert array items into a object back, without using keys?
function pleaseBuy(){
var args = arguments;
for(var i = 0; i < arguments[0].length; ++i) {
args += args[i];
};
};
function getList(){
return ["pepsi","cola","7up"];
}
var list = ({ favorite: "drpepper"}, getList())
pleaseBuy(list)
Expected result:
args = ({ favorite: "drpepper"}, "pepsi", "cola", "7up")
No need for the pleaseBuy function, I'd say:
function getList(){
return ["pepsi","cola","7up"];
}
var list = getList().concat( { favorite: "drpepper" } );
// ^ NB should be :
// or favorite first
var list = [{ favorite: "drpepper" }].concat(getList());
/*
list now contains:
['pepsi, 'cola','7up',{ favorite: "drpepper" }]
*/
An object allways contains key-value pairs. If you want to convert an array to an object, you'll thus have to assign keys and values. For example:
var arr = [1,2,3,4,'some'], arr2Obj = {};
for (var i=0;i<arr.length;i=i+1){
arr2Obj[arr[i]] = i;
}
/*
arr2Obj now contains:
{
1: 0,
2: 1,
3: 2,
4: 3,
some: 4
}
*/
Other example:
var arr = [1,2,3,4,'some'], arr2Numbers = {};
for (var i=0;i<arr.length;i=i+1){
arr2Numbers[arr[i]] = !isNaN(Number(arr[i]));
}
/*
arr2Numbers now contains:
{
1: true,
2: true,
3: true,
4: true,
some: false
}
*/
Do you mean the javascript push function?
Use .unshift() docs to prepend to an array.
var list = getList();
list.unshift( { favorite="drpepper"});
// [{ favorite="drpepper"}, "pepsi", "cola", "7up"]
Demo at http://jsfiddle.net/Ds9y5/
Try this:
var array = ["pepsi","cola","7up"];
array.push({ favorite: "drpepper"});
Or
var array2 = ["pepsi","cola","7up"];
var array = [{favorite: "drpepper"}];
for(var ctr = 0 ; ctr < array2.length ; ctr++){
array.push(array2[ctr]);
}
var s = getList();
s.unshift({ favorite : "drpepper"}); // at the first place in array
s.push({ favorite : "drpepper"}); // at the last place in array
alert(s);
JavaScript push() Method
JavaScript unshift() Method