Javascript-форум (https://javascript.ru/forum/)
-   Элементы интерфейса (https://javascript.ru/forum/dom-window/)
-   -   Получение индекса по значению (https://javascript.ru/forum/dom-window/76634-poluchenie-indeksa-po-znacheniyu.html)

Янковиц 28.01.2019 14:03

Получение индекса по значению
 
Есть массив:
0: [href: "https://images.unsplash.com/photo-1430651717504-ebb9e3e6795e", id: "13", title: "Заголовок"]
1: [href: "https://images.unsplash.com/photo-1458400411386-5ae465c4e57e", id: "52", title: "Заголовок 2"]
2: [href: "https://images.unsplash.com/photo-1460500063983-994d4c27756c", id: "63", title: "Заголовок 3"]
3: [href: "https://images.unsplash.com/photo-1452473767141-7c6086eacf42", id: "47", title: "Заголовок 4"]


Как получить индекс, если известен href и он равен https://images.unsplash.com/photo-14...4-ebb9e3e6795e
заранее спасибо

j0hnik 28.01.2019 14:20

console.log(
    [
      {href: "https://images.unsplash.com/photo-1430651717504-ebb9e3e6795e", id: "13", title: "Заголовок"},
      {href: "https://images.unsplash.com/photo-1458400411386-5ae465c4e57e", id: "52", title: "Заголовок 2"},
      {href: "https://images.unsplash.com/photo-1460500063983-994d4c27756c", id: "63", title: "Заголовок 3"},
      {href: "https://images.unsplash.com/photo-1452473767141-7c6086eacf42", id: "47", title: "Заголовок 4"}
    ].findIndex(el => el.href === "https://images.unsplash.com/photo-1430651717504-ebb9e3e6795e")
);

j0hnik 28.01.2019 14:24

var indHref = (arr, hrf) => arr.findIndex(el => el.href === hrf);

Янковиц 28.01.2019 15:28

Спасибо, работает. Однако в jS компрессоре ругается на строку:
indHref = (lbCollect, source) => lbCollect.findIndex(el => el.href === source);
Invalid assignment (line: 21, col: 32)
Делаю так:
source = [url]https://images.unsplash.com/photo-1430651717504-ebb9e3e6795e;[/url]
lbCollect = [
      {href: "https://images.unsplash.com/photo-1430651717504-ebb9e3e6795e", id: "13", title: "Заголовок"},
      {href: "https://images.unsplash.com/photo-1458400411386-5ae465c4e57e", id: "52", title: "Заголовок 2"},
      {href: "https://images.unsplash.com/photo-1460500063983-994d4c27756c", id: "63", title: "Заголовок 3"},
      {href: "https://images.unsplash.com/photo-1452473767141-7c6086eacf42", id: "47", title: "Заголовок 4"}
    ];
indHref = (lbCollect, source) => lbCollect.findIndex(el => el.href === source);

Янковиц 28.01.2019 15:34

В общем, сделал так:
indHref = lbCollect.findIndex(function(object) {
	return object.href === source;
});


Часовой пояс GMT +3, время: 11:10.